且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

禁止在ASP.NET Core中的API URL上重定向

更新时间:2023-02-15 13:04:39

仅在路径不是API的情况下,将重定向事件处理程序替换为使用默认行为的处理程序.在Startup.ConfigureServices中,添加以下内容:

Replace the redirect event handler with one that uses the default behavior only if the path is not an API. In Startup.ConfigureServices, add this:

services.ConfigureApplicationCookie(options => {
    options.Events.OnRedirectToAccessDenied = ReplaceRedirector(HttpStatusCode.Forbidden, options.Events.OnRedirectToAccessDenied);
    options.Events.OnRedirectToLogin = ReplaceRedirector(HttpStatusCode.Unauthorized, options.Events.OnRedirectToLogin);
});

使用此帮助程序方法替换重定向方法:

Use this helper method to replace the redirect methods:

static Func<RedirectContext<CookieAuthenticationOptions>, Task> ReplaceRedirector(HttpStatusCode statusCode, Func<RedirectContext<CookieAuthenticationOptions>, Task> existingRedirector) =>
    context => {
        if (context.Request.Path.StartsWithSegments("/api")) {
            context.Response.StatusCode = (int)statusCode;
            return Task.CompletedTask;
        }
        return existingRedirector(context);
    };

有了这个,API控制器方法就可以调用Unauthorized()Forbid()而不会导致重定向.

With this in place, the API controller methods can call Unauthorized() and Forbid() without causing redirects.

更新:上面的内容适用于ASP.NET Core2.代码适用于ASP.NET Core 1 不一样.

Update: The above is for ASP.NET Core 2. The code for ASP.NET Core 1 is different.