![](/img/trans.png)
[英]Make a thread to execute certain code every X seconds, in ASP.NET Web API
[英]How to execute code on every request within a controller in ASP.NET Web API 2?
我正在使用ASP.NET Web API2。我有一个BaseController类,所有其他控制器都派生自该类。 我在此控制器中具有以下方法:
protected User GetLoggedInUser()
{
// Get the id of the logged in user.
var globalUserId = userProvider.UserId;
// Return the entity of the logged in user.
return context.Users.FirstOrDefault(u => u.GlobalUserId == globalUserId);
}
这个想法是我在全局设置了一个Authorize属性,并且获得了登录用户的ID。 用户没有存储在我连接的数据库中-我仅从客户端接收他们的ID。 这就是为什么我需要检查数据库中是否存在具有给定GlobalUserId的User实体。 否则,我应该返回401 /未经授权,因为未经授权的用户不能访问这些方法。
我现在正在做的是在所有方法中进行以下检查:
// Get the entity of the logged in user (from the BaseController class).
var userEntity = this.GetLoggedInUser();
// If the user is not found, return 401 / UNAUTHORIZED.
if (userEntity == null)
{
return Unauthorized();
}
有没有一种好的方法来处理此问题,并且不以某种方式在我所有具有Authorize属性的方法中重复相同的代码(如上所述,我已经全局设置了Authorize属性,但是我有几种方法可以具有AllowAnonymous属性,这意味着不是我的所有方法都需要授权)?
我知道MessageHandlers是执行应在每个请求/响应中运行的代码的好方法,但就我而言,我需要检查Authorize / AllowAnonymous属性并与我的数据库建立连接,因此我不确定是一个不错的选择,或根本没有选择。
您可以创建一个自定义的Authorize属性,并使用它代替Authorize属性,并覆盖AuthorizeCore方法。
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
// Get the entity of the logged in user
var userEntity = GetLoggedInUser(httpContext);
// If the user is not found, return false.
if (userEntity == null)
{
return false;
}
}
private User GetLoggedInUser(HttpContextBase httpContext)
{
// return the current user
}
}
并在您的控制器上像这样使用它:
//Custom authentication request
[CustomAuthorizeAttribute]
public ActionResult DoSomething()
//No authentication at all
[AllowAnonymous]
public ActionResult DoSomething
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.