【发布时间】:2015-11-13 03:56:40
【问题描述】:
我正在使用 WebAPI 2 + ASP.NET 身份
在我的 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...
}
}
我正在使用默认路由模板。另一种选择是为授权请求和匿名请求(用适当的数据注释装饰)路由到 2 种不同的方法。
【问题讨论】:
-
你应该可以使用
User.Identity.IsAuthenticated-- 你试过了吗? -
谢谢,这行得通!错过了那个。如果您想输入答案,我会将其标记为正确。
标签: asp.net-identity asp.net-web-api2 asp.net-web-api asp.net-web-api-routing