HttpClient PutAsync不向api发送参数 [英] HttpClient PutAsync doesn't send a parameter to api

查看:463
本文介绍了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发送参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆