Geerten Geerten - 6 months ago 30
ASP.NET (C#) Question

How to remove the redirect from an ASP.NET 5 webapi and return HTTP 401?

Following the answer on this question, I have added authorization on everything by default, using the following code:

public void ConfigureServices(IServiceCollection aServices)
aServices.AddMvc(options =>
var lBuilder = new AuthorizationPolicyBuilder().RequireAuthenticatedUser();

var lFilter = new AuthorizeFilter(lBuilder.Build());


public void Configure(IApplicationBuilder aApp, IHostingEnvironment aEnv, ILoggerFactory aLoggerFactory)
aApp.UseCookieAuthentication(options =>
options.AuthenticationScheme = "Cookies";
options.AutomaticAuthentication = true;

However when someone tries to access something unauthorized, it returns a (what seems a default) redirect URL (

I want it to return a HTTP 401 only, instead of a redirect.

How can I do this in ASP.NET 5 for a WebAPI?


By the url you get redirected to I assume you're using cookie authentication.

You should get the desired results by setting the LoginPath property of the CookieAuthenticationOptions to null or empty as described by one of the users.

app.UseCookieAuthentication(options =>
            options.LoginPath = "";

It was probably working back then but it's not working anymore (because of this change).

I've submitted a bug on GitHub for this.

I'll update the answer once it gets fixed.