【问题标题】:Scaffold Identity UI in ASP.NET Core 2.1 and add Global FilterASP.NET Core 2.1 中的 Scaffold Identity UI 并添加全局过滤器
【发布时间】:2019-05-13 11:45:19
【问题描述】:

我有一个 ASP.NET Core 2.1 应用程序,我在其中使用身份脚手架,如 here 中所述

现在我有一个用于 OnActionExecuting 的全局过滤器

public class SmartActionFilter : IActionFilter
{
    public void OnActionExecuting(ActionExecutingContext filterContext)
    {
        ...
    }
}

在 startup.cs 我配置过滤器如下

public void ConfigureServices(IServiceCollection services)
{
    services
        .AddMvc(options =>
        {
            options.Filters.Add(new AddHeaderAttribute("Author", "HaBo")); // an instance
            options.Filters.Add(typeof(SmartActionFilter)); // by type
            // options.Filters.Add(new SampleGlobalActionFilter()); // an instance
        })
        .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
        .AddJsonOptions(options =>
        {
            options.SerializerSettings.ContractResolver = new DefaultContractResolver();
            options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
        });
}

此过滤器可用于所有操作方法,但不适用于身份区域中的操作方法。如何让全局过滤器对 Identity Area 中的所有页面起作用?

【问题讨论】:

    标签: c# asp.net asp.net-core asp.net-identity


    【解决方案1】:

    Filters in ASP.NET Core 的开头段落中,您将看到以下注释:

    重要

    本主题适用于 Razor 页面。 ASP.NET Core 2.1 及更高版本支持 Razor 页面的 IPageFilterIAsyncPageFilter。如需更多信息,请参阅Filter methods for Razor Pages

    这解释了为什么您的 SmartActionFilter 实现仅针对操作而不是针对页面处理程序执行。相反,您应该按照注释中的建议实现IPageFilterIAsyncPageFilter

    public class SmartActionFilter : IPageFilter
    {
        public void OnPageHandlerSelected(PageHandlerSelectedContext ctx) { }
    
        public void OnPageHandlerExecuting(PageHandlerExecutingContext ctx)
        {
            // Your logic here.
        }
    
        public void OnPageHandlerExecuted(PageHandlerExecutedContext ctx)
        {
            // Example requested in comments on answer.
            if (ctx.Result is PageResult pageResult)
            {
                pageResult.ViewData["Property"] = "Value";
            }
    
            // Another example requested in comments.
            // This can also be done in OnPageHandlerExecuting to short-circuit the response.
            ctx.Result = new RedirectResult("/url/to/redirect/to");
        }
    }
    

    注册SmartActionFilter 仍然按照您的问题中所示的相同方式完成(使用MvcOptions.Filters)。

    如果您想同时为操作 页面处理程序运行它,您可能需要同时实现 IActionFilterIPageFilter

    【讨论】:

    • 有什么方法可以在这里设置 ViewBag 吗?在这个过滤器中?
    • 您无法直接访问ViewBag,但您可以向ViewData 添加属性,这些属性将在页面的cshtml 中使用ViewBag 读取。
    • 这有帮助。希望我也可以从这里控制重定向
    猜你喜欢
    • 2017-05-18
    • 2018-05-12
    • 1970-01-01
    • 2012-03-20
    • 1970-01-01
    • 2019-03-03
    • 2019-07-09
    • 2019-01-31
    • 1970-01-01
    相关资源
    最近更新 更多