angular - 从角度发送数据时,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; }
}
}
解决方案
为了在 ASP.NET Core 中正确绑定 JSON,您必须修改您的操作以[FromBody]
在参数中包含该属性。这告诉框架使用请求的内容类型标头来决定将哪个配置IInputFormatters
用于模型绑定。
public ActionResult<Views.Shipping.Test> CreateShippingDocForm([FromBody] Views.Shipping.Test testInstance)
{
return testInstance; //breakpoint is here
}
推荐阅读
- analytics - Power BI Desktop 导入数据限制
- google-cloud-platform - 如何仅将目录下许多子目录中的文件复制到 GCP 中的另一个项目存储桶中?
- c# - 使用 .Nest() 或 .Read() 时出现 SQLDataReader 错误
- java - 警告:在“OnLifecycleEvent”类型中找不到注释方法“value()”:找不到 android.arch.lifecycle.OnLifecycleEvent 的类文件
- git - GIT存储库的所有文件同时标记为“丢失”和“新文件” [SourceTree]
- polymer-3.x - shady-render.ts:46 Uncaught TypeError: result.getTemplateElement is not a function
- javascript - 由于语法无效 (ASP.NET),服务器无法处理 PUT 请求
- docker - Gitlab-CI 部署阶段和任务因错误的 Rancher API Url 和密钥而失败
- python - ValueError:检查输入时出错:预期 conv1d_1_input 有 3 个维度,但得到了形状为 (3856, 52) 的数组
- ruby-on-rails - 打开从 Angular 上传到 Rails 应用程序的图像时出错