【发布时间】:2019-07-28 01:31:55
【问题描述】:
我有一个 .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 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
}
}
}
.Net核心视图模型:
namespace TrackingSystem.Views.Shipping
{
public class Test
{
public string name { get; set; }
}
}
【问题讨论】:
-
您不必为
application/json手动设置内容标题。这是 Angular 6+ 中的默认设置 -
@Brandon 我注意到了,但我这样做是为了安全。我会在生产前将其删除。谢谢你的收获
-
您能否在浏览器开发工具网络选项卡中看到请求负载为
{ name: 'hello' }?如果是,那么您的 API 肯定有问题。 -
@SiddAjmera 是的,我可以在开发工具中看到它
-
您还应该检查 Postman 是否正确处理了相同的请求。
标签: angular http asp.net-core https asp.net-core-webapi