c# - FromHeaderAttribute 不适用于属性

标签 c# .net asp.net-core

我正在尝试使用 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 配置为 trueStartup.cs 中,如下所示:

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

使用具有以下设置的 Postman 调用发布操作

添加标题: enter image description here

在 Body 中设置值: enter image description here

结果截图: enter image description here

使用 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/

相关文章:

c# - 在 C# 中将 12 小时格式转换为 24 小时格式

c# - StructureMap 强类型构造函数参数

c# - .net c# : Creating a Async Process

c# - 我的 Xpath 有什么问题吗?

c# - 在 ASP.NET 中查找给定周(月)后的日期

c# - WebGet 在功能上是否等同于 WebInvoke(Method = "GET")?

c# - 如何在 ASP.NET Core 3.1 MVC 中进行自定义路由

c# - 发布时如何清除 Razor Page 模型上的绑定(bind)属性?

c# - 使用测试服务器的 .NET 6 E2E 测试在 TeamCity CI 上失败,但工作手动运行

c# - 如果声明是接口(interface),编译器无法识别泛型中的属性