Search code examples
c#asp.net-core.net-corecontrollerasp.net-core-mvc

How to add default route for other requests


Example: I created a controller.cs file as shown here:

using Microsoft.AspNetCore.Mvc;
using ControllersExample.Models;

namespace ControllersExample.Controllers
{
    [Controller]
    public class HomeController : Controller
    {
        [Route("/")]
        [Route("home")]
        public ContentResult home()
        {
            return Content("<h1>Welcome</h1> <h2>Hello from Index</h2>", "text/html");
        }

        [Route("about")]
        public string about()
        {
            return "Hello from about";
        }

        [Route("contact")]
        public string contact()
        {
            return "Hello from contact";
        }
    }
}

In program.cs file, I have:

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers(); //add all controller classes as services

var app = builder.Build();

//app.MapGet("/", () => "Hello World!");


app.UseStaticFiles();   
app.UseRouting();
app.MapControllers();
app.Run();

And I want to define a default route for all other requests hasn't defined above. Eg: I want to access request /abc, /edf, /ghi, ... etc, but I haven't defined these routes.

I tried to add

app.Use(async (context, next) =>
{
    await context.Response.WriteAsync("Page not found");
    await next();
});

at the end of program.cs file but it's not working.

How can I define one time for all other requests?

Thank you all in advance


Solution

  • There is multiple ways to achieve your requirement, I suggest you could consider using the mapfallback method. This adds a specialized Microsoft.AspNetCore.Routing.RouteEndpoint to the Microsoft.AspNetCore.Routing.IEndpointRouteBuilder that will match requests for non-file-names with the lowest possible priority.

    More details, you could refer to below codes:

    ...
    // Fallback route for undefined requests
    app.MapFallback(async (context) =>
    {
        context.Response.StatusCode = 404;
        await context.Response.WriteAsync("404 - Page Not Found");
    });
    
    app.Run();
    

    Result:

    enter image description here