首页 > 解决方案 > 提供自定义标头时的绑定方法

问题描述

所以我试图在 WebAPI 上实现一个 WS,它检查接收到的标头中是否有可选的自定义参数,并处理它及其正文。

我正在和 Postman 一起玩以测试它。当我在标题上调用没有自定义参数的方法时,一切正常。当我在标题中包含我的自定义参数时,我的方法不会触发。

[HttpPost]
        [ResponseType(typeof(ResultModel))]
        public HttpResponseMessage Add([FromBody] InputModel oModel)
        {
            ResultModel oResult;

// Process oModel

// Check if my "X-Custom-Parameter exists
if(Request.Headers.GetValues("X-Custom-Parameter").FirstOrDefault() != null){
 // Do something with custom parameter and oModel
}

            return Request.CreateResponse(HttpStatusCode.OK, oResult);
        }

从邮递员打电话时,我收到以下消息:

Error: Header name must be a valid HTTP Token ["X‐Custom-Parameter"]

和标题:

POST /myapi/path
X‐Custom-Parameter: 123Kartofen
Content-Type: application/json
cache-control: no-cache
Postman-Token: 6d1da8b9-9871-439e-8e5d-79c22978b4cd

虽然我缺少一些配置。我已经在网上冲浪了几个小时并阅读了有关处理程序和过滤器的信息,但我认为这不是我想要的。

标签: c#asp.net-web-api2

解决方案


将您的自定义标头重命名为Custom-Parameter而不是X‐Custom-Parameter。因为不推荐使用应用程序协议中的“X-”前缀

https://tools.ietf.org/search/rfc6648


推荐阅读