1
votes

I have an Api project in that I have 2 different Controllers :

one controller is a System.Web.Mvc controller:

public class HomeController : Controller

in that, I have define a request like below:

var request = System.Web.HttpContext.Current.Request;
                request.Headers.Add("token", "test");

one other controller is a Api controller:

public class CalendarController : ApiController { private string _accessToken;

    public CalendarController()
    {
        IEnumerable<string> accessTokenValues;

        var request = System.Web.HttpContext.Current.Request;

        var token = request.Headers.GetValues("token");
        //var tokenValues = accessTokenValues as string[] ?? accessTokenValues.ToArray();
        //_accessToken = (tokenValues.Any()) ? tokenValues.First() : "";
    } }

I added "token" to the request header but I cannot get it in the Api controller. Please help me ! Thanks!

1
Who is calling the api endpoint ? Whoever calling this api endpoint is supposed to send the header values. Rite? - Shyju
Please explain more detail. my code run in HomeController first to set the token value. Then, I want to get it on the Api Controller - van thanh tran
HTTP is stateless ! What are you trying to achieve by setting the header. Can you elaborate you use case in detail ? - Shyju

1 Answers

1
votes

The originating caller is responsible for setting the request headers. Therefore adding your header on the first request to HomeController means that it will not be added to subsequent requests to CalendarController. Take a look at : https://msdn.microsoft.com/en-us/library/bb470252.aspx for more details about the ASP.NET request response pipeline

Ultimately, it depends on what you want to achieve as to how you might add to the header.

For example, If you have all the information on the server side to add to the request header and you're using OWIN you can add a custom middle-ware layer that will intercept incoming calls and add your custom header as the request makes its way to your controller.(http://www.asp.net/aspnet/overview/owin-and-katana/owin-middleware-in-the-iis-integrated-pipeline)