我实现了 AspNetCore.Authorization 并用 [Authorize]
装饰了 Controller 类。如果我从浏览器调用 Controller ,这会起作用。然而,View Component 可以访问数据:
查看:
@foreach (Category category in Model) {
<a class="btn btn-block
asp-action="Index"
asp-controller="Note"
asp-route-categoryid=@category.CategoryID
asp-route-page="1">
@category.Name
</a>
这导致 View 组件被来自 @category.Name 的数据填充,实际上浏览器的地址栏无法访问。
View 组件:
[Authorize]
public class NavigationMenuViewComponent : ViewComponent
{
private INoteRepository _Repository;
public NavigationMenuViewComponent(INoteRepository repository)
{
_Repository = repository;
}
public IViewComponentResult Invoke()
{
ViewBag.SelectedCategory = RouteData?.Values["category"];
return View(_Repository.Categories
.OrderBy(x => x.Name));
}
}
实际上我认为,如果未实际登录,Authorize
属性将拒绝来自 View 组件的调用。我如何才能实现这种行为?
最佳答案
ViewComponents 不参与 Controller 生命周期,这意味着您不能在 View 组件中使用过滤器。因此,Authorize
过滤器不会被执行。
View 组件必须使用 ViewComponent 类公开的 User 属性(获取当前用户的 System.Security.Principal.IPrincipal。),以根据 User 属性的内容做出决定或更改输出。 根据应用程序使用的身份验证类型,您需要验证用户的凭据。
关于c# - ASP.NET 核心 : calling a view component does not respect authorization attribute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42298016/