Click here to Skip to main content
15,867,308 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
I am trying to read a value from HTTP headers using dotnet core 2.0 controllers. The code that I have is below:
C#
[Route("api/[controller]")]
    public class AuthController : Controller
    {
        private readonly ActionExecutedContext context;
        public AuthController(ActionExecutedContext context)
        {
            this.context = context;
        }

        [HttpGet]
        public string Get()
        {
            var xyz = context.HttpContext.Request?.Headers["Basic"];
            return xyz;
        }
    }


The returning value is nothing. The exception that I have is

InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Mvc.Filters.ActionExecutedContext' while attempting to activate 'Resiliency.API.Controllers.AuthController'.

What should I do in order to read the value from HTTP headers in the dotnet core 2.0?

What I have tried:

I tried
HttpRequest.Headers
Posted
Updated 28-Mar-18 6:28am

1 solution

In your action method, try this:

C#
Request.Headers["myHeaderKeyName"]


BTW, the controller class is reinstantiated with every request, so your stored request value will be null unless you store it a different way.
 
Share this answer
 
v3
Comments
fatihkaratay 28-Mar-18 12:45pm    
this returns null. I tried as Request.Headers["date"] and it returns no content
#realJSOP 28-Mar-18 13:52pm    
Is there a date key in the header? Are you sure you don't actually want a value from the querystring?

Request.QueryString["date"]

On the other hand, the parameters in the querystring are mapped to the action prototype. You shouldn't have to access the querystring directly.
fatihkaratay 28-Mar-18 14:01pm    
What I am actually trying to do is get a username from the cookie that is in the request header. The cookie has userinfo which comes from single sign on service. I need to get user info from this cookie and load the page based on that. I am no sure that I am following the right approach.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900