I am using WEB API 2.0 for REST Service development and I need to pass a parameter from request header to the API controller action method. How can I?

By default API controller is reading the parameters from request body. How can I make it read parameter from request header?

[HttpPost]
[Route("abc")]
public IHttpActionResult abcMethod(string s)
{
   //some code
}

I want the above abcMethod to read it's parameter from request header.

Pls suggest.

有帮助吗?

解决方案

How about this...

IEnumerable<string> headerValues = request.Headers.GetValues("MyCustomID");
var id = headerValues.FirstOrDefault();

其他提示

I'm still new to the Web API 2, but I usually do

string variale = this.Request.Headers.GetValues("HeaderParameter").First();

Any of the FirstOrDefault, Single, SingleOrDefault() or anything of the like will work.

Also, Lambda works as well:

string variable = this.Request.Headers.First(header => header.Key == "Parameter").Value.FirstOrDefault();
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top