在asp.net核心中将字典发布到web api

时间:2016-08-29 20:07:17

标签: c# asp.net-web-api asp.net-core coreclr

我使用Asp.Net Core开发了简单的web api,我试图使用HttpClient发布键值对。我尝试了两种方法。

第一种方法

[Route("api/[controller]/[action]")]
public class TransformationController : Controller
{
    private IServiceResolver _serviceResolver;
    public TransformationController(IServiceResolver serviceResolver)
    {
        _serviceResolver = serviceResolver;
    }       

    [HttpPost]
    [ActionName("Post1")]
    public void Post1([FromBody]Dictionary<string, string> data)
    {
       // do something
    }
}

然后我将其发布如下

    [Fact]
    public void TestPost1()
    {
        var content = new Dictionary<string, string>();
        content.Add("firstname", "foo");            
        var httpContent = new FormUrlEncodedContent(content);

        var client = new HttpClient();
        var result = client.PostAsync("http://localhost:17232/api/Transformation/Post1", httpContent).GetAwaiter().GetResult();
    }

但我收到Unsupported Media Type错误

  

{StatusCode:415,ReasonPhrase:&#39;不支持的媒体类型&#39;,版本:   1.1,内容:System.Net.Http.StreamContent,Headers:{Date:Mon,29 Aug 2016 19:44:44 GMT Server:Kestrel X-SourceFiles:   =?UTF-8 2 B 4 QzpccmVwb3NcY3ItbWV0YXRhc2tlclxzcmNcSW5ib3VuZEludGVncmF0aW9uXFRyYW5zZm9ybWF0aW9ucy5BcGlcYXBpXFRyYW5zZm9ybWF0aW9uXFRyYW5zZm9ybWF0aW9uMQ ==?=   X-Powered-By:ASP.NET Content-Length:0}}

方法2
由于我无法在FormUrlEncodedContent中指定内容类型和编码,因此我更改了post方法的签名,现在它将Json字符串作为参数。想法是将字符串反序列化为字典。

    [HttpPost]
    [ActionName("Post2")]
    public void Post2([FromBody]string data)
    {
        var dictionary = JsonConvert.DeserializeObject<Dictionary<string, string>>(data);
     // do something here

     }

然后我发布如下字符串

    [Fact]
    public void TestPost2()
    {   
        var httpContent = new StringContent("{ \"firstName\": \"foo\" }", Encoding.UTF8, "application/json");

        var client = new HttpClient();
        var result = client.PostAsync("http://localhost:17232/api/Transformation/Post2", httpContent).GetAwaiter().GetResult();
    }

但是当我调试测试时; Post2方法中的data参数为null。

我不确定我在这两种方法中都缺少什么?有人可以帮忙吗

UPDATE1
如果我使用POSTMAN发布数据然后它的工作。因此对于方法1,我可以将原始数据发布为

{
  "firstname": "foo"
}

和Approach2将原始数据发布为

 "{\"firstname\": \"foo\"}"

当我使用HttpClient

时,相同的数据是如何工作的

1 个答案:

答案 0 :(得分:7)

尝试合并两种方法:

[Fact]
public void TestPost3()
{   
    var httpContent = new StringContent("{ \"firstName\": \"foo\" }", Encoding.UTF8, "application/json");

    var client = new HttpClient();
    var result = client.PostAsync("http://localhost:17232/api/Transformation/Post3", httpContent).GetAwaiter().GetResult();
}

[HttpPost]
[ActionName("Post3")]
public void Post3([FromBody]IDictionary<string, string> data)
{
   // do something
}