是的,您可以在UI和控制器之间的中间层检查特定用户是否可以访问请求的控制器。
/
我们需要在我们的视图中的某个地方添加Async方法
/
@if (await Url.HasAccessToController(urlActionContext))
{
<p>You have access</p>
}
方法的实施:
public static async Task<bool> HasAccess(this IUrlHelper Helper, UrlActionContext ActionContext, string httpMethod = "GET" )
{
//U need to Implement this method as per your needs
var httpContext = Helper.ActionContext.HttpContext;
var routeValues = new RouteValueDictionary(ActionContext.Values);
routeValues["action"] = ActionContext.Action;
routeValues["controller"] = ActionContext.Controller;
var path = Helper.Action(ActionContext);
var features = new FeatureCollection();
features.Set<IHttpRequestFeature>(new HttpRequestFeature()
{
Method = httpMethod,
Path = path,
});
var ctx = new DefaultHttpContext(features);
var routeContext = new RouteContext(ctx);
foreach (var entry in routeValues)
{
routeContext.RouteData.Values.Add(entry.Key, entry.Value);
}
var actionSelector = httpContext.RequestServices.GetRequiredService<IActionSelector>();
var provider = httpContext.RequestServices.GetRequiredService<IActionDescriptorCollectionProvider>();
var actionDescriptors = actionSelector.SelectCandidates(routeContext);
var actionDescriptor = actionSelector.SelectBestCandidate(routeContext, actionDescriptors);
var authService = httpContext.RequestServices.GetRequiredService<IAuthorizationService>();
var ok = await authService.AuthorizeAsync(httpContext.User, actionDescriptor, "YOUR_POLICY");
return ok;
}