我正在尝试使用 FromHeaderAttribute 绑定(bind)模型属性根据文档,这应该适用于参数和属性。
不幸的是,出于某种原因,我无法让它为 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
最佳答案
如果要将 Request Header 的值绑定(bind)到模型的某个属性,则需要在 ConfigureServices
中将 SuppressInferBindingSourcesForParameters
配置为 true
在 Startup.cs
中,如下所示:
services.AddMvc().ConfigureApiBehaviorOptions(options => {
options.SuppressInferBindingSourcesForParameters = true;
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
使用具有以下设置的 Postman 调用发布操作
使用 powershell 调用 post Action ,改变你的 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"
关于c# - FromHeaderAttribute 不适用于属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58038884/