本文介绍了ASPNET核心和Angular2页面刷新问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ASP.Net核心应用程序,仅用于Web API,并且具有Angular 2前端.当我将路由添加到angular应用并导航到Angular中的某个路由时,它会导航,但是当我刷新页面时,出现页面未找到错误.我在配置方法中有以下内容

I have an ASP.Net core app that is used only for web API and has Angular 2 front end. When I added routing to angular app and navigate to some route in Angular it navigates, but when I do a refresh of the page, I get page not found error.I have the following in configure method

    app.Use(async (context, next) =>
        {
            await next();

            if (context.Response.StatusCode == 404
                && !Path.HasExtension(context.Request.Path.Value))
            {
                context.Request.Path = "/index.html";
                context.Response.StatusCode = 200;
                await next();
            }
        });

我试图添加重写规则,例如使用Asp.net 4.5进行Angular2路由

I tried to add rewrite rules like inAngular2 routing with Asp.net 4.5

这样做时,我会收到客户端错误

I get client side errors, when I do that

感谢您的帮助.谢谢

推荐答案

您的代码比真正的管理程序更难看.

Your code is more of an ugly fix than a real management.

您需要进行设置,以使路由在服务器端进行托管,然后根据需要从客户端进行正确的管理.

You need to make it so that your route is managed server-side and then managed correctly from your client-side as you want it.

当我在ASP.NET/Angular2项目中使用MVC时,我做到了这一点,以便可以使用FallBackRoute管理不是API调用的URL.

As I was using MVC in my ASP.NET / Angular2 project, I made it so that my URLs that would not be API calls would be managed with a FallBackRoute.

        app.UseMvc(r =>
        {   
            r.MapRoute(
                name: "default",
                template: "{controller}/{path?}/{action}/{id?}",
                defaults: new { controller = "Home", action = "Index" }
            );
            r.MapSpaFallbackRoute(
                name: "spa-fallback",
                defaults: new { controller = "Home", action = "Index" }
            );
        });

这样,在刷新或手动加载URL时,将加载我的index.cshtml并加载Angular2 Core,该Angular2 Core随后将通过路由器管理所需的路由.

That way, on refresh or manual URL load, my index.cshtml would be loaded and load the Angular2 Core that would then manage the wanted route with the router.

与观察404错误相比,这是一件好事.

This is imho a better thing to do than watching for 404 errors.

这篇关于ASPNET核心和Angular2页面刷新问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-25 03:03