Modify User property in MVC Controller vs ApiController

时间:2015-07-28 22:16:51

标签: c# asp.net-mvc

I have a custom IPrincipal called UserPrincipal which I use within my controllers. I use a base controller to set the User then implement that base controller within all my other MVC controllers. My BaseController:

public class BaseController : Controller
{
    protected virtual new UserPrincipal User
    {
        get { return HttpContext.User as UserPrincipal; }
    }
}

That works perfectly well however now I am attempting to setup an API using using the ApiController class. I would like those ApiControllers to use the same UserPrincipal so I have essentially copied and pasted the same code into a BaseApiController class:

public class BaseApiController : ApiController
{
    protected virtual new UserPrincipal User
    {
        get { return HttpContext.User as UserPrincipal; }
    }
}

This second version has a Compiler error at HttpContext.User stating the following:

Cannot access non-static property 'User' in static context.

What is different about the ApiController from Controller and why am I getting this error?

3 个答案:

答案 0 :(得分:2)

ApiController already has a property called User which returns an IPrincipal

MSDN: ApiController.User Property

If I correctly understand what you wish to do, then I believe that you should be able to leverage this property without adding any custom code or other properties.

答案 1 :(得分:1)

在David Tansey的回答的帮助下,我找到了这个解决方案。而不是HttpContext.User我使用base.User

public class BaseApiController : ApiController
{
    protected virtual new UserPrincipal User
    {
        get { return base.User as UserPrincipal ?? new UserPrincipal("defaultuser"); }
    }
}

我添加了null检查并提供了一个默认用户,因为如果用户未登录并且我不想null经常检查,那么转换将导致null在我的申请中。

答案 2 :(得分:0)

Try setting the principal. See http://www.asp.net/web-api/overview/security/authentication-and-authorization-in-aspnet-web-api for more information.

private void SetPrincipal(IPrincipal principal)
{
    Thread.CurrentPrincipal = principal;
    if (HttpContext.Current != null)
    {
        HttpContext.Current.User = principal;
    }
}

Also look into Token-based authentication.