在Asp.net Core中将字典发布到Web API [英] Posting dictionary to web api in asp.net core

查看:388
本文介绍了在Asp.net Core中将字典发布到Web API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用Asp.Net Core开发的简单Web api,并且我尝试使用HttpClient发布键值对.我尝试了两种方法.

I have simple web api developed using Asp.Net Core and I am trying to post key-value pair using HttpClient. I tried two approaches.

第一种方法

[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,标头:{日期:2016年8月29日星期一19:44:44 GMT服务器:Kestrel X-SourceFiles: =?UTF-8?B?QzpccmVwb3NcY3ItbWV0YXRhc2tlclxzcmNcSW5ib3VuZEludGVncmF0aW9uXFRyYW5zZm9ybWF0aW9ucy5BcGlcYXBpXFRyYWWFZZm9b9 X技术支持:ASP.NET内容长度:0}}

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

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

Approach 2
Since I cannot specify content type and encoding in FormUrlEncodedContent I changed the signature of the post method, and now it take Json string as parameter. Idea is to de-serialize the string into dictionary.

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

     }

然后我将字符串发布如下

and then I am posting the string as below

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

however when I debug the test; the data parameter in Post2 method is null.

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

I am not sure what I'm missing here in both approaches? Can someone please help

更新1
如果我使用POSTMAN发布数据,那么它的工作原理.因此,对于方法1,我可以将原始数据发布为

Update1
If I use POSTMAN to post data then its working. So for Approach 1 I can post raw data as

{
  "firstname": "foo"
}

和Approach2将原始数据发布为

and Approach2 post raw data as

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

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

howevere the same data is not working when I use 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
}

这篇关于在Asp.net Core中将字典发布到Web API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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