How to throw ForbiddenException in ASP.NET Core 2 Instead of using AccessDeniedPath

不羁岁月 提交于 2019-12-06 04:32:05

The code for redirecting to AccessDeniedPath is handled by CookieAuthenticationEvents.OnRedirectToAccessDenied, included here for completeness:

public Func<RedirectContext<CookieAuthenticationOptions>, Task> OnRedirectToAccessDenied { get; set; } = context =>
{
    if (IsAjaxRequest(context.Request))
    {
        context.Response.Headers["Location"] = context.RedirectUri;
        context.Response.StatusCode = 403;
    }
    else
    {
        context.Response.Redirect(context.RedirectUri);
    }
    return Task.CompletedTask;
};

In order to override this behavior, you can provide your own implementation of OnRedirectToAccessDenied, that can either write to the response or, in your case, throw an exception. To do that, you can use something like the following:

services.AddAuthentication(...)
    .AddCookie(options => {
        // ...
        options.Events.OnRedirectToAccessDenied = context => {
            // Your code here.
            // e.g.
            throw new YouAreNotWelcomeHereException();
        };
    });

Here, context is an instance of RedirectContext, which (through its inheritance tree), contains properties such as:

Using these properties, you can obtain any information you need about the incoming request. You can also write your own response, etc.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!