c# - HttpClient PutAsync 不向 api 发送参数

标签 c# asp.net-mvc-3 json.net

在 Controller 上Put如下:

[HttpPut]
[ActionName("putname")]
public JsonResult putname(string name)
{
    var response = ...
    return Json(response);  
}

问题出在通过以下方式使用此 API 时

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;
    }

此代码不会将参数名称传递给 Controller ​​。我什至尝试将 uri 更改为/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; }
} 

-斯坦

关于c# - HttpClient PutAsync 不向 api 发送参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10489611/

相关文章:

c# - Parallel.ForEach(task.Wait) 和 Task.WaitAll 的区别

c# - 为什么在尝试通过序列化为 JSON 来打印对象时缺少某些成员?

c# - protobuf-net 不适合哪些场景?

c# - 在前端获取 "Top clause contains invalid value"错误,但在 SQL 数据中清晰可见

asp.net-mvc-3 - C# lock 关键字,我想我用错了

c# - ASP.NET MVC 3 - microsoft-web-helpers v1.1 的问题

c# - 字典 <string,string> 使用 Automapper 映射到一个对象

c# - 使用 JSON.NET 库在 JArray 中查找节点 (JObject)

c# - 反序列化 json 字符串以获得多个结果

c# - 是否有 WPF 复选框控件切换事件?