[英]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.