[英]Override routing in ASP.NET CORE 2.2 to implicitly route to an area if user have some permissions
如果用户具有某种权限,我正在寻找一种简单的方法来稍微改变路由行为并将额外的区域数据添加到路由数据中。
假设对于普通用户 url site/shop/12
应该路由到ShopController
但对于管理员,它应该路由到AdminArea/ShopController
请考虑这个问题不是关于 HTTP 重定向,而是关于在框架级别扩展基础设施以允许路由或控制器调用的额外功能
您可以使用URL 重写中间件来重定向管理员用户的请求
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)
);
向处理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" });
}
我认为最好的方法是在前端设置正确的 URL,然后在端点上验证请求,执行如下操作:
[HttpGet]
[Route("v1.0/download/document")]
public IActionResult download_document(int id, string token)
{
try
{
if (token == null || isNotAdmin(token))
return Unauthorized();
这样您的端点就会受到保护,并且您可以避免重定向。 另外,在我看来,前端的一切都更有意义
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.