测试请求是匿名的还是经过身份验证的WebAPI 2 +身份

Pat*_*ick 1 asp.net-web-api asp.net-web-api-routing asp.net-identity asp.net-web-api2

我正在使用WebAPI 2 + ASP.NET Identity

在我的ApiController方法之一中,我想测试特定的HTTP请求是否来自经过身份验证的客户端(即,该请求是否包含授权标头)。

以下工作,但是也许有更好的方法?

private AuthContext db = new AuthContext();

// GET api/Orders/
[AllowAnonymous]
public async Task<IHttpActionResult> GetOrder(int id)
{
    // ApplicationUser is an IdentityUser.
    ApplicationUser currentUser = null;

    try
    {
        UserManager<ApplicationUser> userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));
        currentUser = await userManager.FindByNameAsync(User.Identity.GetUserName());
    }
    catch (Exception)
    {
    }

    if ( currentUser == null )
    {
        // Anonymous request.
        // etc...




    } else {
        // Authorized request.
        // etc...
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在使用默认的路由模板。另一个选择是将两种方法路由到授权请求和匿名请求(用适当的数据注释装饰)。

Dav*_*sey 5

ApiControllerWebApi中的类中有一个User属性(您已经在代码中使用它了:)User.Identity.GetUserName()

User属性是一个IPrincipal实例,该实例的属性Identity是的实例IIdentity

ApiController方法的代码中,您可以通过测试的IsAuthenticated属性来测试当前请求的用户是否已通过身份验证User.Identity

例如:

if ( User.Identity.IsAuthenticated == true)
{
    // Authenticated user...do something
}
else
{
   // anonymous..do something different
}
Run Code Online (Sandbox Code Playgroud)