简体   繁体   中英

.NET Core WebAPI - 404 fallback with attribute routing

While implementing my first restful webapi in .NET Core 3.1 I am trying to implement a fallback routine for 404 Errors. My Startup.cs is actual looking like this:

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();
    // ...
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // ...
    app.UseRouting();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
        endpoints.MapFallbackToController("EndpointNotFound", "Fallback");
    });
}

In this configuration, the 404 fallback takes effect before the actual route to the respective controller. I am using the attribute routing in the api controllers. Is it generally possible to use the MapFallbackToController() method inside attribute routing? If not, is there an useful middleware alternative to it?

Greetings

Some options are available to implement this you can start from this and explore other possibilities (The following are configured in Configure method in Startup.cs):

Option 1 app.UseStatusCodePages(); this will show the builtin default pages.

Option 2 app.UseStatusCodePagesWithRedirects("~/MyCustomController/{0}"); the placeholder {0} will populate with the HttpStatusCode eg: 404

This method is commonly used when the app:

  • Should redirect the client to a different endpoint, usually in cases where > a different app processes the error. For web apps, the client's browser address bar reflects the redirected endpoint.
  • Shouldn't preserve and return the original status code with the initial redirect response.

Option 3 app.UseStatusCodePagesWithRedirects("~/MyCustomController/{0}"); same with Option 2 with some difference

This method is commonly used when the app should:

  • Process the request without redirecting to a different endpoint. For web apps, the client's browser address bar reflects the originally requested >endpoint.
  • Preserve and return the original status code with the response.

You can use this as a reference for more broad detail in handling errors Handle errors in ASP.NET Core

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM