简体   繁体   English

ASP.NET Core 防止 api 路由的 spa 回退路由

[英]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.我的前端有一个带有 Vue.js 的 ASP.NET Core 2.2 应用程序。 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.问题出在我的 API 路由上。 When the API URL exists we have no problem, but when the URL doesn't exist, it goes to the spa-fallback routes.当 API URL 存在时,我们没有问题,但是当 URL 不存在时,它会转到spa-fallback路由。

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?有没有办法设置路由,以便当 URL 以/api/开头并且没有找到路由时,它返回 404 而不是 spa-fallback?

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我害怕不是因为你为你的 SPA 定义了一条后备路线,所以 .Net 核心试图做的是寻找那条路线,如果那条路线不存在,它将转到 spa 后备路线

Here is how you can intercept with the API request in the line以下是如何拦截该行中的 API 请求

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

We fixed this issue by splitting up the project into a .UI and .API project.我们通过将项目拆分为.UI.API项目来解决此问题。 Each have there own IoC container, routes, ...每个都有自己的 IoC 容器、路由、...

Seperated projects also have the advantage to publish them into seperated application pools or on different servers.分离的项目还具有将它们发布到分离的应用程序池或不同服务器上的优势。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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