我有以下代碼,它使用策略要求來查看用戶是否有權訪問特定的 matchKey。這是我的控制器操作
[HttpGet]
[Authorize(Policy = Policy.Match)]
public async Task<IActionResult> Index(Guid matchKey)
{
var model = await _mediator.Send(new MatchIndexQuery
{
MatchKey = matchKey
});
return View("Index", model);
}
我從 request.query 得到 matchKey,一切都按預期作業。
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, MatchRequirement requirement)
{
if (context.Resource is HttpContext httpContext)
{
var query = httpContext.Request.Query;
if (query.TryGetValue("matchKey", out StringValues matchKeyString))
{
if (Guid.TryParse(matchKeyString.ToString(), out Guid matchKey))
{
// Do some checks here and return
context.Succeed(requirement);
}
}
}
}
這一切都有效,現在我想讓我的 URL 更好一點,這樣我就可以使用 /Match/{matchKey} 而不是 /Match?matchKey={matchKey} 所以我有以下路線。
[HttpGet]
[Authorize(Policy = Policy.Match)]
[Route("[controller]/{matchKey?}")]
[Route("[controller]/[action]/{matchKey?}")]
public async Task<IActionResult> Index(Guid matchKey)
{
var model = await _mediator.Send(new MatchIndexQuery
{
MatchKey = matchKey
});
return View("Index", model);
}
但是現在我的策略不起作用,因為 {matchKey} 不再出現在 Request.Query 中,而是作為 Request.Path 的一部分。
是否有任何統一的方法可以在我的策略中獲取 {matchKey},或者如果我在查詢中找不到它,我是否需要基于 Request.Path 進行一些字串拆分?
uj5u.com熱心網友回復:
或者如果我在查詢中找不到它,我是否需要一些基于 Request.Path 的字串拆分?
是的,您可以拆分httpContext.Request.Path并獲取matchKey.
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, MatchRequirement requirement)
{
if (context.Resource is HttpContext httpContext)
{
var path = httpContext.Request.Path.ToString().Split("/");
//if Path contains matchKey,httpContext.Request.Path.ToString() will be /controllername/actionname/matchkeyvalue,and the length of path will be 4
if (path.Length==4)
{
var matchKeyString=path[path.Length - 1];
if (Guid.TryParse(matchKeyString.ToString(), out Guid matchKey))
{
// Do some checks here and return
context.Succeed(requirement);
}
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/372574.html
上一篇:ASP.NETCore-如何將IdentityDbContext中的ApplicationUserid作為UserId插入到員工模型中
