本文介绍了C#.net Core Web API Post参数始终为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这真让我发疯.我正在做一些非常简单的操作,将POST请求发送到我的Web API.端点设置如下:

So this is driving me nuts. I'm doing something very simple sending POST request to my web api. The endpoint is set up as follows:

[HttpPost]
[Route("locations")]
public async Task<IActionResult> PostLocations([FromBody]IEnumerable<Location>locations)

我正在按如下方式拨打电话:

and I'm making the call as follows:

http://localhost:60254/api/Fetch/locations
With the body 
{
  "Locations": [
    { 
        "LocationId": "111", 
        "ProductId": 110, 
        "Sku": "11131-LJK" 
    }
  ]
}

And header: content-type: application/json

再次,这是非常简单的事情,应该立即可用,并且这种棘手的框架更改将所有事情搞砸了.

now again, this is VERY simple something that should work out of the box and this fricking framework change is messing everything up.

现在,如果我获得HttpContext并直接读取正文流

Now, if I get the HttpContext and read the body stream directly

    using (StreamReader reader = new StreamReader(HttpContext.Request.Body, Encoding.UTF8))
    {
      string  body = reader.ReadToEnd();
    }

我可以看到正文已正确发送,我有一个格式良好的json,可以将其转换为所需的任何内容.所以问题是我想念这个端点不起作用了吗?

I can see the body being sent correctly, I have a super well formed json that I can transform into whatever I want. So the question is what am I missing that this endpoint doesn't work?

Web api项目模板没有为开箱即用添加什么配置?

What configuration the web api project template is not adding out of the box for this to work?

推荐答案

您的有效负载不是Location的列表,而是具有Locations属性的列表的对象.

Your payload is not a list of Location but an object with a Locations property that's a list.

代替

{
  "Locations": [
   { 
      "LocationId": "111", 
      "ProductId": 110, 
      "Sku": "11131-LJK" 
   }
 ]
}

使用

 [
   { 
     "LocationId": "111", 
     "ProductId": 110, 
     "Sku": "11131-LJK" 
   }
 ]

这篇关于C#.net Core Web API Post参数始终为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-27 15:37