C# FromHeaderAttribute不';我不为物业工作
我正在尝试绑定模型属性,根据文档,该属性应该适用于参数和属性 不幸的是,由于某些原因,我无法使其在PUT/POST请求模型中的属性上工作:C# FromHeaderAttribute不';我不为物业工作,c#,.net,asp.net-core,C#,.net,Asp.net Core,我正在尝试绑定模型属性,根据文档,该属性应该适用于参数和属性 不幸的是,由于某些原因,我无法使其在PUT/POST请求模型中的属性上工作: public class TestModel { [FromBody] public string Value { get; set; } // The property I want to be bound from header [FromHeader(Name = "Or
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如果您想将请求头的值绑定到模型的一个属性,您需要在
Startup.cs
中将SuppressInferBindingSourcesForParameters
配置为true
,如下所示:
services.AddMvc().ConfigureApiBehaviorOptions(options => {
options.SuppressInferBindingSourcesForParameters = true;
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
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"
使用具有以下设置的邮递员调用post操作
添加标题:
在正文中设置值:
结果的屏幕截图:
使用powershell调用post操作,如下所示更改身体:
services.AddMvc().ConfigureApiBehaviorOptions(options => {
options.SuppressInferBindingSourcesForParameters = true;
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
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"
我做了一个演示来测试您的代码,属性上使用的
FromHeader
运行良好,是我的工作演示,您可以参考并检查差异。如果你仍然有这个问题,你能分享一个可以重现这个问题的演示吗?@XueliChen,对不起,我不能通过你的链接下载这个演示,它说我没有权限。这是我的测试示例的链接:你太棒了!我认为我们需要将PR纳入现有的.net文档中,以明确如何让它工作。谢谢