在 asp.net 核心中将词典发布到网络 api

Posting dictionary to web api in asp.net core

我使用 Asp.Net Core 开发了简单的 Web api,我正在尝试使用 HttpClient post 键值对。我尝试了两种方法。

第一种方法

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

然后我post如下

    [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: 'Unsupported Media Type', Version: 1.1, Content: System.Net.Http.StreamContent, Headers: { Date: Mon, 29 Aug 2016 19:44:44 GMT Server: Kestrel X-SourceFiles: =?UTF-8?B?QzpccmVwb3NcY3ItbWV0YXRhc2tlclxzcmNcSW5ib3VuZEludGVncmF0aW9uXFRyYW5zZm9ybWF0aW9ucy5BcGlcYXBpXFRyYW5zZm9ybWF0aW9uXFRyYW5zZm9ybWF0aW9uMQ==?= X-Powered-By: ASP.NET Content-Length: 0 }}

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

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

     }

然后我post输入如下字符串

    [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 参数为空。

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

更新1
如果我使用 POSTMAN 来 post 数据然后它的工作。所以对于方法 1,我可以 post 原始数据作为

{
  "firstname": "foo"
}

和Approach2 post原始数据为

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

但是当我使用 HttpClient 时相同的数据不起作用

尝试合并两种方法:

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