我有一个.Net Core 2.2 Web api,它正在侦听一个角度的前端。我从角度服务将 JSON 数据发送到后端,我在 chrome 开发工具和小提琴手中检查数据,所以我很清楚要发送什么。端点被击中,但正文未解析,我的后端认为它是空的。我已经查看了堆栈溢出上的人们遇到的类似问题,但他们的解决方案似乎都不起作用(FormBody,更改发送的数据等(。这是我来自小提琴手的数据包数据,我的前端代码和我的webAPI/viewmodel。我在 C# 端点中放置了一个断点,它被命中,但"testInstance"对象始终为 null。知道为什么这是,也许是字符编码吗?
提琴手数据
生:
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 Core Web 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
}
}
}
.净核心视图模型:
namespace TrackingSystem.Views.Shipping
{
public class Test
{
public string name { get; set; }
}
}
ASP.NET Core 中正确绑定 JSON,您必须修改操作以在参数中包含属性[FromBody]
。这会告知框架使用请求的内容类型标头来决定将哪个已配置的IInputFormatters
用于模型绑定。
public ActionResult<Views.Shipping.Test> CreateShippingDocForm([FromBody] Views.Shipping.Test testInstance)
{
return testInstance; //breakpoint is here
}