[英]FromHeaderAttribute doesn't work for properties
I am trying to bind model property using FromHeaderAttribute which according to documentation should work for parameter and properties.我正在尝试使用FromHeaderAttribute绑定 model 属性,根据文档,该属性应该适用于参数和属性。
Unfortunately, for some reason I cannot get it working for properties in PUT/POST request models:不幸的是,由于某种原因,我无法让它适用于 PUT/POST 请求模型中的属性:
public class TestModel
{
[FromBody]
public string Value { get; set; }
// The property I want to be bound from header
[FromHeader(Name = "Origin")]
public string Origin { get; set; }
}
[HttpPost]
public void Post(
TestModel value,
[FromHeader] string origin)
{
Console.WriteLine(value.Origin); // always empty
Console.WriteLine(value.Value); // OK
Console.WriteLine(origin); // OK
}
Asp.Net Core App v2.2.0 Asp.Net Core App v2.2.0
If you want to bind the value of Request Header to one property of the model, you need to configure SuppressInferBindingSourcesForParameters
as true
in ConfigureServices
in Startup.cs
like below:如果要将 Request Header 的值绑定到 model 的一个属性,则需要在
Startup.cs
的ConfigureServices
中将SuppressInferBindingSourcesForParameters
配置为true
,如下所示:
services.AddMvc().ConfigureApiBehaviorOptions(options => {
options.SuppressInferBindingSourcesForParameters = true;
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
Use the Postman with the below settings to call the post action使用具有以下设置的 Postman 调用后期操作
Set the value in Body:在 Body 中设置值:
The screenshot of result:结果截图:
Use powershell to call the post action,change your Body like below:使用 powershell 调用 post 动作,改变你的 Body 如下:
Invoke-WebRequest `
-Method 'POST' `
-Uri "http://localhost:50112/api/values" `
-Headers @{"Pragma"="no-cache"; "Cache-Control"="no-cache"; "Origin"="http://localhost" } `
-Body ("test"|ConvertTo-Json) `
-ContentType "application/json"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.