本文介绍了HttpClient PutAsync不向api发送参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在控制器上的放置如下:
On the controller Put is as following:
[HttpPut] [ActionName("putname")] public JsonResult putname(string name) { var response = ... return Json(response); }问题在于通过以下方式使用此API时
The issue is on the when consuming this API via following
using (httpClient = new HttpClient()) { string name = "abc"; string jsonString = JsonConvert.SerializeObject(name); var requestUrl = new Uri("http:...../controller/putname/"); using (HttpContent httpContent = new StringContent(jsonString)) { httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); HttpResponseMessage response = httpClient.PutAsync(requestUrl, httpContent).Result; }此代码不会将参数名称传递给控制器.我什至尝试将uri更改为/putname/"+名称.
This code doesn't pass the parameter name to controller. I even tried changeing uri to /putname/" + name.
推荐答案这对我有用:
var jsonString = "{\"appid\":1,\"platformid\":1,\"rating\":3}"; var httpContent = new StringContent(jsonString, Encoding.UTF8, "application/json"); var message = await _client.PutAsync(MakeUri("App/Rate"), httpContent); Assert.AreEqual(HttpStatusCode.NoContent, message.StatusCode);和我的操作方法:
public void PutRate(AppRating model) { if (model == null) throw new HttpResponseException(HttpStatusCode.BadRequest); if (ModelState.IsValid) { // .. } }和模型
public class AppRating { public int AppId { get; set; } public int PlatformId { get; set; } public decimal Rating { get; set; } }-斯坦
更多推荐
HttpClient PutAsync不向api发送参数
发布评论