14

I have an Intranet application with Windows authentication based on MVC4.

When I need the WindowsIdentity for authorization purpose in a Controller I just use

 HttpContext.User.Identity

Now I wanted to use the new Asp.Net WebAPI for some Ajax calls.

Is there a way to get the WindowsIdenty object in the same easy way as in an MVC Controller?

1 Answer 1

24

Please don't reference the HttpContext from a controller.

You can access the Controllers User property which is way of accessing the Identity through without a dirrect reference to HttpContext.

public class MyController : ApiController
{
    public string Get()
    {
         var indenty = this.User.Identity;
    }
}

Why

The controllers User property provides a level of abstraction which allows for easier mocking and thus unit testing. This abstraction also allows for greater portability e.g. if this was WebApi Self Host you wouldn't even have access to HttpContext.

To read more about how to unit test and mock the User property read here. For more information re: portability read here.

Sign up to request clarification or add additional context in comments.

3 Comments

One small clarification: If you want the Identity use User.Identity
Well I appreciate the clarity of the answer, it would be for everyone's edification if you explained WHY one wouldn't reference HttpContext from a controller.
@dansan thanks for the comment. I have put a brief explanation as to why.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.