FromHeaderAttribute不适用于属性

时间:2019-09-21 09:16:16

标签: c# .net 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
    }

Asp.Net Core App v2.2.0

1 个答案:

答案 0 :(得分:1)

如果要将请求标头的值绑定到模型的一个属性,则需要将true的{​​{1}}中的ConfigureServices配置为Startup.cs,如下所示:

services.AddMvc().ConfigureApiBehaviorOptions(options => {
            options.SuppressInferBindingSourcesForParameters = true;
        }).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

使用具有以下设置的邮递员来调用发布操作

添加标题: enter image description here

在“正文”中设置值: enter image description here

结果的屏幕截图: enter image description here

使用powershell调用后期操作,如下所示更改您的身体:

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"
相关问题