Replace the redirect event handler with the one that uses the default behavior only if the path is not an API. In Startup.ConfigureServices add the following:
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 redirection 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); };
In this case, the methods of the API controller can call Unauthorized() and Forbid() , without causing redirection.
Update: Above for ASP.NET Core 2. The code for ASP.NET Core 1 is different.
Edward brey
source share