当前位置: 首页>>代码示例>>C#>>正文


C# HttpClient.PutAsJsonAsync方法代码示例

本文整理汇总了C#中System.Net.Http.HttpClient.PutAsJsonAsync方法的典型用法代码示例。如果您正苦于以下问题:C# HttpClient.PutAsJsonAsync方法的具体用法?C# HttpClient.PutAsJsonAsync怎么用?C# HttpClient.PutAsJsonAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Net.Http.HttpClient的用法示例。


在下文中一共展示了HttpClient.PutAsJsonAsync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Update

 public ContactsDto Update(ContactsDto contactsDto)
 {
     using (var client = new HttpClient())
     {
         HttpResponseMessage response =
             client.PutAsJsonAsync("http://localhost:9372/api/ContactsApi/"+ contactsDto.Id, contactsDto).Result;
         return response.Content.ReadAsAsync<ContactsDto>().Result;
     }
 }
开发者ID:Maricano,项目名称:VOLLEYTEAM-Esbjerg,代码行数:9,代码来源:ContactGatewayService.cs

示例2: GetLocation

        public async void GetLocation()
        {
            Geoposition pos = await _geolocator.GetGeopositionAsync();
            var pin = new MapIcon()
            {
                Location = pos.Coordinate.Point,
                Title = "You are here!",
                Image = RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/Image/Location_Icon.png")),
                NormalizedAnchorPoint = new Point() { X = 0.32, Y = 0.78 },
            };
            map.MapElements.Add(pin);
            await map.TrySetViewAsync(pos.Coordinate.Point, 15);
            (App.Current as App).User.user_x = pos.Coordinate.Point.Position.Latitude.ToString();
            (App.Current as App).User.user_y = pos.Coordinate.Point.Position.Longitude.ToString();
            using (var client = new HttpClient())
            {
                try
                {
                    client.BaseAddress = new Uri(@"http://pubbus-coeus.azurewebsites.net/");
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    HttpResponseMessage response = await client.PutAsJsonAsync("api/users/" + (App.Current as App).User.user_id, (App.Current as App).User);

                    //Printf("Da cap nhat vi tri: " + (App.Current as App).User.user_x + ":" + (App.Current as App).User.user_y);
                }
                catch (Exception ex)
                {
                    Printf(ex.Message);
                }
            }
        }
开发者ID:pubbus,项目名称:Projects,代码行数:31,代码来源:Map_Control.xaml.cs

示例3: UpdateProduct

 static bool UpdateProduct(ProductViewModel newProduct)
 {
     HttpClient client = new HttpClient();
     client.BaseAddress = new Uri(baseURL);
     var response = client.PutAsJsonAsync("api/Products/", newProduct).Result;
     client.Dispose();
     return response.Content.ReadAsAsync<bool>().Result;
 }
开发者ID:SreekanthSPillai,项目名称:refFramework,代码行数:8,代码来源:ProductAPI.cs

示例4: Update

 public Rating Update(Rating Rating)
 {
     using (var client = new HttpClient())
     {
         HttpResponseMessage response =
             client.PutAsJsonAsync("http://localhost:17348/api/Rating/" + Rating.Id, Rating).Result;
         return response.Content.ReadAsAsync<Rating>().Result;
     }
 }
开发者ID:atamas88,项目名称:Finaldinal,代码行数:9,代码来源:RatingGatewayService.cs

示例5: Update

 public Company Update(Company company)
 {
     using (var client = new HttpClient())
     {
         HttpResponseMessage response =
             client.PutAsJsonAsync("http://localhost:17348/api/company/" + company.Id, company).Result;
         return response.Content.ReadAsAsync<Company>().Result;
     }
 }
开发者ID:atamas88,项目名称:Finaldinal,代码行数:9,代码来源:CompanyGatewayService.cs

示例6: Main

        public void Main(string[] args)
        {
            var config = new Configuration().AddEnvironmentVariables();
            string urlOptimizer = config.Get("URLOptimizerJobs") ?? "http://localhost:5004/api/Jobs/";
            Console.WriteLine("Mortgage calculation service listening to {0}", urlOptimizer);

            bool WarnNoMoreJobs = true;
            while (true)
            {
                try
                {
                    var httpClient = new HttpClient();
                    httpClient.DefaultRequestHeaders.Accept.Clear();
                    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    List<Job> jobs = httpClient.GetAsync(urlOptimizer).Result.Content.ReadAsAsync<List<Job>>().Result;

                    List<Job> remainingJobs = jobs.FindAll(j => !j.Taken);
                    if (remainingJobs.Count == 0)
                    {
                        if (WarnNoMoreJobs)
                        {
                            Console.WriteLine("No more jobs !");
                            WarnNoMoreJobs = false;
                        }
                        Task.Delay(1000).Wait();
                        continue;
                    }
                    else
                    {
                        Console.WriteLine("{0} job(s) remaining", remainingJobs.Count);
                        WarnNoMoreJobs = true;
                    }
                    Random engine = new Random(DateTime.Now.Millisecond);
                    Job Taken = remainingJobs[engine.Next(remainingJobs.Count)];
                    Taken.Taken = true;
                    httpClient.PutAsJsonAsync<Job>(urlOptimizer + Taken.Id, Taken).Result.EnsureSuccessStatusCode();

                    // The calculation is completely simulated, and does not correspond to any real financial computing
		    // We thus only wait for a given delay and send a random amount for the total cost
		    // Should one be interested in the kind of computation that can truly use scaling, one can take a look
		    // at the use of Genetic Algorithms as shown as in https://github.com/jp-gouigoux/PORCAGEN
                    Task.Delay(20).Wait();
                    Taken.Done = true;
                    Taken.TotalMortgageCost = Convert.ToDecimal(engine.Next(1000));

                    httpClient.PutAsJsonAsync<Job>(urlOptimizer + Taken.Id, Taken).Result.EnsureSuccessStatusCode();
                }
                catch
                {
                    Task.Delay(1000).Wait();
                }
            }
        }
开发者ID:booking59,项目名称:mortgage,代码行数:53,代码来源:Program.cs

示例7: AddFinance

 public ActionResult AddFinance(SearchFinanceModel model)
 {
     Session["Finance"] = null;
     IEnumerable<FinanceModel> objBE;
     using (var client = new HttpClient())
     {
         model.addFinance.insertUserId = base.CurrentUserID;
         client.BaseAddress = new Uri(System.Configuration.ConfigurationManager.AppSettings["APIURI"]);
         client.DefaultRequestHeaders.Accept.Add(
             new MediaTypeWithQualityHeaderValue("application/json"));
         HttpResponseMessage response = client.PutAsJsonAsync("finance/SaveFinanceActivity", model.addFinance).Result;
         if (response.IsSuccessStatusCode)
         {
             string jsonResult = response.Content.ReadAsStringAsync().Result;
             if (!string.IsNullOrEmpty(jsonResult) && !jsonResult.Equals("[]"))
             {
                 objBE = JsonConvert.DeserializeObject<IEnumerable<FinanceModel>>(jsonResult);
                 model.addFinance.finance = objBE;
             }
             else
                 model.addFinance.finance = null;
         }
         model.activityType = (IEnumerable<SelectListItem>)Session["ActivityType"];
         model.processorCompany = (IEnumerable<SelectListItem>)Session["Processor"];
         model.addFinance.activityType = (IEnumerable<SelectListItem>)Session["ActivityType"];
         model.addFinance.processorCompany = (IEnumerable<SelectListItem>)Session["Processor"];
         ViewBag.SuccessMsg = Pecuniaus.Resources.Finance.Finance.FinanceAddedSuccessfully;
     }
     return View("Index", model);
 }
开发者ID:rayanc,项目名称:Pecuniaus,代码行数:30,代码来源:MerchantFinanceController.cs

示例8: User_Is_Added_To_Queue

        public void User_Is_Added_To_Queue()
        {
            var client = new HttpClient();

            string name = "hello";
            string key = Convert.ToString(Guid.NewGuid());
            string format = "https://qcue-live.firebaseio.com/queues/{0}/{1}.json";

            string uri = String.Format(format, key, name);

            var queue = new Q
            {
                ShortCode = "TEST",
                Users = new Dictionary<string, QUser>
                 {
                    {
                        Convert.ToString(Guid.NewGuid()),
                        new QUser
                        {
                            Id = "red",
                            State = "waiting"
                        }
                    }
                 }
            };

            var json = JsonConvert.SerializeObject(queue);
            var result = client.PutAsJsonAsync(uri, queue).Result;

            result.EnsureSuccessStatusCode();
        }
开发者ID:TeamKillScreen,项目名称:qcue.website,代码行数:31,代码来源:RawFirebaseTests.cs

示例9: RunClient

        /// <summary>
        /// Runs an HttpClient issuing a POST request against the controller.
        /// </summary>
        static async void RunClient()
        {
            var handler = new HttpClientHandler();
            handler.Credentials = new NetworkCredential("Boris", "xyzxyz");
            var client = new System.Net.Http.HttpClient(handler);

            var bizMsgDTO = new BizMsgDTO
            {
                Name = "Boris",
                Date = DateTime.Now,
                User = "Boris.Momtchev",
            };

            // *** POST/CREATE BizMsg
            Uri address = new Uri(_baseAddress, "/api/BizMsgService");
            HttpResponseMessage response = await client.PostAsJsonAsync(address.ToString(), bizMsgDTO);

            // Check that response was successful or throw exception
            // response.EnsureSuccessStatusCode();

            // BizMsg result = await response.Content.ReadAsAsync<BizMsg>();
            // Console.WriteLine("Result: Name: {0}, Date: {1}, User: {2}, Id: {3}", result.Name, result.Date.ToString(), result.User, result.Id);
            Console.WriteLine(response.StatusCode + " - " + response.Headers.Location);

            // *** PUT/UPDATE BizMsg
            var testID = response.Headers.Location.AbsolutePath.Split('/')[3];
            bizMsgDTO.Name = "Boris Momtchev";
            response = await client.PutAsJsonAsync(address.ToString() + "/" + testID, bizMsgDTO);
            Console.WriteLine(response.StatusCode);

            // *** DELETE BizMsg
            response = await client.DeleteAsync(address.ToString() + "/" + testID);
            Console.WriteLine(response.StatusCode);
        }
开发者ID:BorisMomtchev,项目名称:NiCris.Dashboard-.NET-4.5,代码行数:37,代码来源:Program.cs

示例10: ProcessAsync

        public async Task<IEnumerable<Event>> ProcessAsync(Event evnt)
        {
            var importRecordExtracted = evnt.GetBody<ImportRecordExtracted>();
            var elasticSearchUrl = _configurationValueProvider.GetValue(Constants.ElasticSearchUrlKey);

            var client = new HttpClient();
            var url = string.Format("{0}/import/{1}/{2}", elasticSearchUrl,
                importRecordExtracted.IndexType,
                importRecordExtracted.Id);
            var responseMessage = await client.PutAsJsonAsync(url, importRecordExtracted);

           if (!responseMessage.IsSuccessStatusCode)
            {
                throw new ApplicationException("Indexing failed. " 
                    + responseMessage.ToString());
            }

            return new[]
            {
                new Event(new NewIndexUpserted()
                {
                    IndexUrl = url
                }) 
            };
        }
开发者ID:csuffyy,项目名称:BeeHive,代码行数:25,代码来源:RecordImporterActor.cs

示例11: AddActivityGoal

        public async Task AddActivityGoal()
        {
            var session = await Login();
            var currentSeed = Guid.NewGuid();

            using (var client = new HttpClient { BaseAddress = new Uri(ServerUrl) })
            {
                client.AcceptJson().AddSessionHeader(session.Id);

                var form = new Activity { Name = $"Name.{currentSeed}", Description = $"Description.{currentSeed}" };

                // Add Activity with valid data
                var activityResponse = await client.PostAsJsonAsync($"/api/activities", form);
                Assert.Equal(HttpStatusCode.Created, activityResponse.StatusCode);

                var activity = await activityResponse.Content.ReadAsJsonAsync<Activity>();
                Assert.Equal($"Name.{currentSeed}", activity.Name);

                var goalForm = new ActivityGoalForm { Description = $"Description.{currentSeed}" };
                activityResponse = await client.PutAsJsonAsync($"/api/activities/{activity.Id}/goal", goalForm);
                Assert.Equal(HttpStatusCode.OK, activityResponse.StatusCode);

                activity = await activityResponse.Content.ReadAsJsonAsync<Activity>();
                Assert.Equal(1, activity.Goals.Count);
            }
        }
开发者ID:playgenhub,项目名称:rage-sga-server,代码行数:26,代码来源:ActivitiesControllerTest.cs

示例12: RunAsync_Update

        static async Task RunAsync_Update()
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("http://localhost:2614/");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                try
                {
                    VideoDTO video = new VideoDTO { title = "shen-demo" };
                    HttpResponseMessage response = await client.PutAsJsonAsync("Videoes/ca161757-8196-4454-ae26-d0d70e9cb679", video);
                    response.EnsureSuccessStatusCode();

                    if (response.IsSuccessStatusCode)
                    {
                        VideoDTO videoDTO = await response.Content.ReadAsAsync<VideoDTO>();
                    }
                }
                catch (Exception ex)
                {
                    Console.Write(ex.Message);
                }

            }
        }
开发者ID:dianyitongxiao,项目名称:WebApiClient,代码行数:26,代码来源:Program.cs

示例13: sendReservationDataEdit

 private async void sendReservationDataEdit()
 {
     HttpClient client = new HttpClient();
     string URL = "http://92.221.124.167";
     client.BaseAddress = new Uri(URL);
     HttpResponseMessage response = await client.PutAsJsonAsync("/rest/edit/reservation", reservation).ContinueWith((postTask) => postTask.Result.EnsureSuccessStatusCode());
     this.Close();
 }
开发者ID:Werevector,项目名称:DAT154,代码行数:8,代码来源:ReservationEditorWindow.xaml.cs

示例14: Update

 public void Update(Customer cus)
 {
     using (var client = new HttpClient())
     {
         HttpResponseMessage response =
             client.PutAsJsonAsync(ServerAddress.Address + "customer/", cus).Result;
     }
 }
开发者ID:nordtorp95,项目名称:MovieShopUser,代码行数:8,代码来源:CustomerGateway.cs

示例15: Update

 public void Update(Login login)
 {
     using (var client = new HttpClient())
     {
         HttpResponseMessage response =
             client.PutAsJsonAsync(ServerAddress.Address + "login/", login).Result;
     }
 }
开发者ID:nordtorp95,项目名称:MovieShopUser,代码行数:8,代码来源:LoginGateway.cs


注:本文中的System.Net.Http.HttpClient.PutAsJsonAsync方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。