.Net app.UseAuthorization() blocks some error pages
Since I’m using the app.UseAuthorization() for an automatic authentication, it also block some error check api and my customized 404 not found page. for example when I am trying to visit localhost/RouteNotExist which is not a real URL, It should return me a 404 page rather than redirect me to the /Account/Login. Is there a way to solve this problem, or I should just not use UseAuthorization()?
Edit: this is my Configure method:
public virtual void Configure(IApplicationBuilder app) { app.UseNewRelicLowerCasePath(); app.UseCustomExceptionHandler(); app.UseCustomStatusCodePagesWithReExecute(); app.UseForwardedHeaders(); app.UseWebOptimizer(); app.UseStaticFiles(); app.UseRouting(); app.UseIdentityServer(); app.UseCookiePolicy(); app.UseAuthentication(); app.UseSession(); app.UseCustomSession(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); endpoints.MapControllers(); }); } public static IApplicationBuilder UseCustomExceptionHandler(this IApplicationBuilder app) { app.UseWhen(context => !IsApi(context), builder => { builder.UseExceptionHandler("/Home/Error"); }); app.UseWhen(context => IsApi(context), builder => { builder.UseExceptionHandler("/api/error/500"); }); return app; }
and isApi() method returns a bool says if the url starts with "/api".
Add [AllowAnonymous]
attribute on your public controllers (the error and notfound). You can use this attribute at class or method level, to indicate netcore authentication should not be performed when processing those requests.
More info about authorization attributes on this MSDN link
Beware that if you use [AllowAnonymous]
at class level, any [Authorize]
on a method inside that class won’t work because [AllowAnonymous]
takes precedence.