3
votes

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?

3

3 Answers

1
votes

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("");
    }
}
0
votes

I'm affraid not because you are define a fallback route for your SPA so what .Net core trying to do is look for that route if that is not exist it will go to spa-fallback

Here is how you can intercept with the API request in the line

if (context.Request.Path.Value.StartsWith("/api"))

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseHsts();
        }

        app.UseHttpsRedirection();

        app.Use(async (context, next) =>
        {
            if (context.Request.Path.Value.StartsWith("/api"))
            {
                await context.Response.WriteAsync("Hello");
            }
        });
        app.UseMvc();
    }
0
votes

We fixed this issue by splitting up the project into a .UI and .API project. Each have there own IoC container, routes, ...

Seperated projects also have the advantage to publish them into seperated application pools or on different servers.