c# - ASP.NET 核心 : calling a view component does not respect authorization attribute

标签 c# asp.net-core asp.net-core-viewcomponent

我实现了 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/

相关文章:

c# - C#中假设的可能性

asp.net-core - 向 ASP.NET Core Web API 服务发送 "application/octet-stream"时发布请求错误

c# - 从ViewComponent返回自定义html

c# - 在 API 调用上显示等待或微调器

c# - 如何阻止 1 个解决方案启动您的所有网站?

c# - 将列表作为 XElement 传递以用作 XML 数据类型参数

c# - IHostedService 的优雅关闭

c# - ASP.NET 5 Web Api 基于 token 的身份验证

javascript - Ajax ViewComponent 触发多次

c# - ASPNET CORE ViewComponent 的 TagHelper 不工作