Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Core prevent spa-fallback route for api routes

I have a ASP.NET Core 2.2 application with Vue.js for my frontend. In my startup I have the following routes:

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "mvc",
                template: "{controller=Home}/{action=Index}/{id?}");
            // TODO: When api route doesn't exists it goes into the spa-fallkback route. We need to prevent this.
            routes.MapSpaFallbackRoute(
                name: "spa-fallback",
                defaults: new { controller = "Home", action = "Index" });
        });

The problem is with my API routes. When the API URL exists we have no problem, but when the URL doesn't exist, it goes to the spa-fallback routes.

Is there a way to set up the routes so that when the URL starts with /api/ and no route is found, it returns a 404 instead of the spa-fallback?

like image 853
Mivaweb Avatar asked Nov 28 '25 07:11

Mivaweb


1 Answers

You can always create a catch-all action manually:

public class HomeController : Controller
{
    // SPA Fallback
    public IActionResult Index()
    {
        return View();
    }

    // Disable all other /api/* routes.
    [Route("/api/{**rest}")]
    public IActionResult Api()
    {
        return NotFound("");
    }
}
like image 198
Mariusz Jamro Avatar answered Nov 30 '25 19:11

Mariusz Jamro