LP1*_*P13 3 c# asp.net-web-api coreclr asp.net-core
我有简单的web api开发使用Asp.Net Core,我试图使用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
}
}
Run Code Online (Sandbox Code Playgroud)
然后我发布如下
[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();
}
Run Code Online (Sandbox Code Playgroud)
但我收到了Unsupported Media Type错误
{StatusCode:415,ReasonPhrase:'Unsupported Media Type',版本:1.1,内容:System.Net.Http.StreamContent,标题:{Date:Mon,29 Aug 2016 19:44:44 GMT Server:Kestrel X-SourceFiles: ?= UTF-8乙QzpccmVwb3NcY3ItbWV0YXRhc2tlclxzcmNcSW5ib3VuZEludGVncmF0aW9uXFRyYW5zZm9ybWF0aW9ucy5BcGlcYXBpXFRyYW5zZm9ybWF0aW9uXFRyYW5zZm9ybWF0aW9uMQ == = X-已启动通过:???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
}
Run Code Online (Sandbox Code Playgroud)
然后我发布如下字符串
[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();
}
Run Code Online (Sandbox Code Playgroud)
但是当我调试测试时; dataPost2方法中的参数为null.
我不确定这两种方法中我都缺少什么?有人可以请帮助
UPDATE1
如果我使用邮递员发布的数据,然后它的工作.因此对于方法1,我可以将原始数据发布为
{
"firstname": "foo"
}
Run Code Online (Sandbox Code Playgroud)
和Approach2将原始数据发布为
"{\"firstname\": \"foo\"}"
Run Code Online (Sandbox Code Playgroud)
当我使用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
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9584 次 |
| 最近记录: |