【问题标题】:Override routing in ASP.NET CORE 2.2 to implicitly route to an area if user have some permissions如果用户具有某些权限,则覆盖 ASP.NET CORE 2.2 中的路由以隐式路由到某个区域
【发布时间】:2019-02-26 14:04:07
【问题描述】:

如果用户具有某种权限,我正在寻找一种简单的方法来稍微改变路由行为并将额外的区域数据添加到路由数据中。

假设普通用户 url site/shop/12 应该路由到 ShopController

但对于管理员来说,它应该路由到AdminArea/ShopController


请注意,这个问题不是关于 HTTP 重定向的,而是关于在框架级别扩展基础架构以允许路由或控制器调用的额外功能

【问题讨论】:

    标签: asp.net-core asp.net-core-mvc asp.net-core-routing


    【解决方案1】:

    您可以使用URL Rewriting Middleware 重定向管理员用户的请求

    1.创建重定向规则:

    public class RewriteRules
    {
        public static void RedirectRequests(RewriteContext context)
        {
            //Your logic
            var IsAdminRole = context.HttpContext.User.IsInRole("Admin");
            if (IsAdminRole)
            {
                var request = context.HttpContext.Request;
                string area = "AdminArea";
                var path = request.Path.Value;
    
                //Add your conditions of redirecting
                if(path.Split("/")[1] != area)// If the url does not start with "/AdminArea"
                {
                    context.HttpContext.Response.Redirect($"/{area}{ request.Path.Value }");
                }                          
            }
        }
    }
    

    2.在Startup Configure方法中使用中间件:

    app.UseAuthentication();//before the Rewriter middleware
    
    app.UseRewriter(new RewriteOptions()
                .Add(RewriteRules.RedirectRequests)
                );
    

    【讨论】:

      【解决方案2】:

      将逻辑添加到处理site/shop/12 的控制器方法中,以检查用户是否是管理员,如果是,则重定向到正确的管理区域和控制器。

      var isAdmin = IsUserAnAdmin();
      
      if (isAdmin) {
      
          // This will redirect to the Index method defined in the ShopController
          // in the area name AdminArea
          return RedirectToAction("Index", "Shop", new { Area = "AdminArea" });
      
      }
      

      【讨论】:

      • 当然我不想这样做以避免显式重定向。问题是通过路由来解决这个问题。
      • 路由在 ASP .NET Core 框架中非常严格。如果你想通过路由处理这个问题,你将不得不通过路由中间件的路由:azurecoder.net/2017/07/09/routing-middleware-custom-irouter
      【解决方案3】:

      我认为最好的方法是在前端设置正确的 URL,然后在端点上验证请求,如下所示:

              [HttpGet]
              [Route("v1.0/download/document")]
              public IActionResult download_document(int id, string token)
              {
                  try
                  {
                      if (token == null || isNotAdmin(token))
                          return Unauthorized();
      

      这样您的端点就会受到保护并且您可以避免重定向。另外,在我看来,前端的一切都更有意义

      【讨论】:

        猜你喜欢
        • 2014-05-03
        • 2019-07-21
        • 1970-01-01
        • 2018-06-30
        • 2015-06-24
        • 1970-01-01
        • 2021-06-23
        • 1970-01-01
        • 2021-05-04
        相关资源
        最近更新 更多