Nic*_*ain 3 .net c# asp.net-core
我正在尝试使用FromHeaderAttribute绑定模型属性,根据文档,该属性应该适用于参数和属性。
不幸的是,由于某种原因,我无法让它适用于 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
}
Run Code Online (Sandbox Code Playgroud)
Asp.Net Core 应用程序 v2.2.0
如果您想将请求标头的值绑定到模型的一个属性,您需要SuppressInferBindingSourcesForParameters如下true配置ConfigureServices:Startup.cs
services.AddMvc().ConfigureApiBehaviorOptions(options => {
options.SuppressInferBindingSourcesForParameters = true;
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
Run Code Online (Sandbox Code Playgroud)
使用具有以下设置的 Postman 来调用 post 操作
使用 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"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2838 次 |
| 最近记录: |