首页 > 解决方案 > 从角度发送数据时,web-api POST body 对象始终为空

问题描述

我有一个正在监听角度前端的 .Net Core 2.2 Web api。我从 Angular 服务将 JSON 数据发送到后端,我在 chrome 开发工具和提琴手中检查数据,所以我很清楚正在发送什么。端点被击中,但正文没有解析,我的后端认为它为空。我看过堆栈溢出的人遇到的类似问题,但他们的解决方案似乎都不起作用(FormBody、更改发送的数据等)。这是我来自提琴手的数据包数据、我的前端代码和我的 webAPI/viewmodel。我在我的 C# 端点中放置了一个断点,它被命中,但“testInstance”对象始终为空。知道为什么会这样,也许是字符编码?

提琴手数据

生的:

POST https://localhost:44380/api/Shipping/shippingDoc HTTP/1.1
Host: localhost:44380
Connection: keep-alive
Content-Length: 16
Pragma: no-cache
Cache-Control: no-cache
Accept: application/json, text/plain, */*
Origin: https://localhost:44380
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36
Content-Type: application/json; charset=UTF-8
Referer: https://localhost:44380/dataentry
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9

{"name":"hello"}

文本视图:

{"name":"hello"}

Angular 8 前端服务:

@Injectable({
  providedIn: 'root'
})
export class ShippingService {

  private shippingURL : string = 'api/Shipping/shippingDoc';
  constructor(private http: HttpClient) { }

  postShippingDocForm(shippingDoc : ShippingDoc) : Observable<any> {
    var headers = new HttpHeaders().set('Content-Type', 'application/json; charset=utf-8');
    var test = {name: "hello"} //dummy data
    return this.http.post(this.shippingURL, test, {headers: headers});
  }
}

.Net 核心网络 API:

namespace TrackingSystem.Controllers
    {
        [Route("api/Shipping")]
        public class ShippingController : ControllerBase
        {

            [HttpPost("shippingDoc")]
            [ProducesResponseType(StatusCodes.Status201Created)]
            [ProducesResponseType(StatusCodes.Status400BadRequest)]
            public ActionResult<Views.Shipping.Test> CreateShippingDocForm(Views.Shipping.Test testInstance) 
            {
                return testInstance; //breakpoint is here
            }

        }
    }

.Net核心视图模型:

namespace TrackingSystem.Views.Shipping
{
    public class Test
    {
        public string name { get; set; }
    }
}

标签: angularhttpasp.net-corehttpsasp.net-core-webapi

解决方案


为了在 ASP.NET Core 中正确绑定 JSON,您必须修改您的操作以[FromBody]在参数中包含该属性。这告诉框架使用请求的内容类型标头来决定将哪个配置IInputFormatters用于模型绑定。

public ActionResult<Views.Shipping.Test> CreateShippingDocForm([FromBody] Views.Shipping.Test testInstance) 
{
    return testInstance; //breakpoint is here
}

推荐阅读