提供自定义标头时的绑定方法

时间:2019-04-06 16:07:35

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

因此,我试图在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

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

2 个答案:

答案 0 :(得分:0)

将您的自定义标头重命名为自定义参数,而不是 X-自定义参数。因为不建议使用应用协议中的“ X-”前缀

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

答案 1 :(得分:0)

检查邮递员,是否要发送带连字符或下划线的标头。 X_或X-?