user16768946
user16768946

Reputation: 113

How to properly access HTTP Headers from your controller? (.NET Web App)

I am currently developing a .NET Web App (MVC), and it is designed such that the user logs into the app in another web app, then the IIS passes control to my web app (I call it SP). SP then needs to access headers passed to it containing user information passed from the login page. These fields are then used to add the user to a database for logging purposes. This behavior is called in the constructor from the main controller of the Web App: HomeController because I would like it to run whenever a user accesses the page.

This is my current implementation:

public HomeController()
{
    try
    {
        string ID = Request.Headers.Get("CN userName");

        if (ID.Length > 3)
        {
            try
            {
                ID = ID.Substring(3, 3);
            }
            catch
            {
                ID = ID.Substring(0, 3);
            }
        }
        string firstName = Request.Headers.Get("X-First Name");
        string lastName = Request.Headers.Get("X-Last Name");
        string email = Request.Headers.Get("X-Mail");
        currUser = new User(ID, firstName, lastName, email, "");            }
    catch (Exception e)
    {
        currUser = new User(/*Create Default User*/);
    }
}

The User constructor handles methods needed to manage the User after creation. However, this currently throws an error when deployed when it attempts to access any of the headers. I do not have a lot of experience working with headers so I spent hours attempting to find a solution online, but nothing I tried accomplished what I needed it to. I would appreciate assistance in solving this issue and implementing this behavior properly.

Upvotes: 0

Views: 957

Answers (1)

Ian
Ian

Reputation: 303

I don't think you should do this in a controllers constructor (not sure it's safe either).

It's probably better suited to an Filter, which will make it far easier to reuse.

Upvotes: 1

Related Questions