在asp.net core中向web api发布字典

本文关键字:布字典 字典 api net asp core 中向 web | 更新日期: 2023-09-27 18:04:48

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

1方法

[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: '不支持的媒体类型',版本:1.1、内容:System.Net.Http。StreamContent, Headers: {Date: Mon, 29 Aug 2016 19:44:44 GMT服务器:Kestrel X-SourceFiles:utf - 8 = ? B 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参数为空

我不确定在这两种方法中我错过了什么?有人能帮帮忙吗?

Update1
如果我使用邮差发布数据,那么它的工作。对于方法1,我可以将原始数据发布为

{
  "firstname": "foo"
}

和Approach2将原始数据作为

 "{'"firstname'": '"foo'"}"

然而,当我使用HttpClient

在asp.net core中向web api发布字典

相同的数据不工作

尝试合并两种方法:

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