I need to pass a parameter from request header to the API controller action method. How can I?

StackOverflow https://stackoverflow.com/questions/23467446

سؤال

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