ASP.NET 5 MVC 6: How to configure startup to send a html file when not on any mvc route

与世无争的帅哥 提交于 2019-12-10 18:48:47

问题


I'm building a SPA application using React-Router to handle the front-end routing.

I'm trying to configure the ASP.NET 5 Startup.cs file to use MVC but when a route does not match any of my API routes to send the index.html file so that it will be able to handle react-routers browser history implementation as stated here.

So far i've only been able to get it to send the index.html file when on the default route, i.e. nothing after the localhost:3000.

My Startup Configure method so far. Thank you

        app.UseIdentity();
        app.UseIISPlatformHandler();
        app.UseDefaultFiles(new DefaultFilesOptions {
            DefaultFileNames = new List<string> { "index.html"}
        });
        app.UseStaticFiles();
        app.UseMvc();

回答1:


Pretty simple, with app.UseStatusCodePagesWithReExecute("/");

public void Configure(IApplicationBuilder app)
{
    app.UseIISPlatformHandler();

    app.UseStatusCodePagesWithReExecute("/");

    app.UseDefaultFiles();
    app.UseStaticFiles();
    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}"
        );
    });
}

This will return the index.html page in your wwwroot, even if you get a 404. It will however only change the page, but not the URL.

Alternatively, you might not want to do a page redirect since you are doing a SPA, but if you really need to update the URL you can just do a simple redirect from a controller, like so:

public class RedirectController : Controller
{
    public IActionResult Index()
    {
        return Redirect(Url.Content("~/"));
    }
}

and then in your startup update this:

app.UseStatusCodePagesWithReExecute("/redirect");


来源:https://stackoverflow.com/questions/34494464/asp-net-5-mvc-6-how-to-configure-startup-to-send-a-html-file-when-not-on-any-mv

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!