简体   繁体   English

如何在ASP.NET Web API 2中的控制器上的每个请求上执行代码?

[英]How to execute code on every request within a controller in ASP.NET Web API 2?

I'm using ASP.NET Web API 2. I have a BaseController class that all other controllers derive from. 我正在使用ASP.NET Web API2。我有一个BaseController类,所有其他控制器都派生自该类。 I have the following method in this controller: 我在此控制器中具有以下方法:

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);
}

The idea is that I have an Authorize attribute set globally and I get the Id of the logged in user. 这个想法是我在全局设置了一个Authorize属性,并且获得了登录用户的ID。 The users are not stored in the database that I'm connected with - I'm receiving just their Ids from the client. 用户没有存储在我连接的数据库中-我仅从客户端接收他们的ID。 That's why I need to check whether a User entity with the given GlobalUserId exists in my database. 这就是为什么我需要检查数据库中是否存在具有给定GlobalUserId的User实体。 Otherwise, I should return 401 / Unauthorized, because unauthorized users should not have access to the methods. 否则,我应该返回401 /未经授权,因为未经授权的用户不能访问这些方法。

What I'm doing now is I make the following check in all of my methods: 我现在正在做的是在所有方法中进行以下检查:

// 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();
}

Is there a good way to handle this and somehow not repeat the same code in all of my methods that have an Authorize attribute (as I've wrote above, I've set the Authorize attribute globally, but I have a couple of methods that have the AllowAnonymous attribute, meaning not all of my methods require authorization)? 有没有一种好的方法来处理此问题,并且不以某种方式在我所有具有Authorize属性的方法中重复相同的代码(如上所述,我已经全局设置了Authorize属性,但是我有几种方法可以具有AllowAnonymous属性,这意味着不是我的所有方法都需要授权)?

I know that MessageHandlers are a good way to execute code that should be run in every request/response but in my case I need to check for the Authorize/AllowAnonymous attributes and have a connection to my database, so I'm not sure that this is a good option or an option at all. 我知道MessageHandlers是执行应在每个请求/响应中运行的代码的好方法,但就我而言,我需要检查Authorize / AllowAnonymous属性并与我的数据库建立连接,因此我不确定是一个不错的选择,或根本没有选择。

You can create a custom authorize attribute and use it instead of the Authorize attribute and override AuthorizeCore method. 您可以创建一个自定义的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
       }
    }

And use it on your controllers like this: 并在您的控制器上像这样使用它:

//Custom authentication request
[CustomAuthorizeAttribute]
public ActionResult DoSomething()

//No authentication at all
[AllowAnonymous]
public ActionResult DoSomething

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在 ASP.NET Web API 中创建一个线程每 X 秒执行一次特定代码 - Make a thread to execute certain code every X seconds, in ASP.NET Web API 读取ASP.NET WEB API中的每个传入请求(URL) - Reading every incoming request (URL) in ASP.NET WEB API ASP.NET Web API请求未达到控制器操作 - ASP.NET Web API request does not reach controller action 每个请求都调用ASP.NET Web API控制器构造函数 - ASP.NET Web API controller constructor called with each request 如何在Asp.net Web API 2中在运行时的每个请求中添加配置设置? - How to add configuration setting with every request on runtime in Asp.net Web api 2? 如何“克隆”传入的ASP.NET MVC Multipart请求以发送到Web API控制器 - How to 'clone' an incoming ASP.NET MVC Multipart request to send to a Web API controller 我如何在ASP.NET Web API中记录原始HTTP请求,而不管它是否路由到控制器? - How do I log the raw HTTP request in ASP.NET Web API whether or not it routes to a controller? 如何使用Unity基于http请求参数动态地将服务注入到asp.net web api控制器中 - How to dynamically inject service into asp.net web api controller based on http request parameter using Unity 如何在 ASP.NET Web ZDB974238714CA8DE634A7CE1D083A 中的 Controller 操作中处理取消? - How to handle cancellation in Controller actions in ASP.NET Web API? 如何从控制器调用方法-ASP.NET Web API - how to call method from controller - asp.net web api
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM