首页 文章

在ASP.NET Core RC2中重写URL

提问于
浏览
10

如何在ASP.NET Core RC2中完成URL重写?当我刷新页面时,从RC1迁移到RC2打破了我的Angular 2路由 .

我之前在我的wwwroot中的web.config中使用了这样的规则 . 使用RC2,我甚至不确定我是否应该在我的wwwroot中有一个web.config,或者我是否应该在我的项目的基础上有一个 .

这是我的基础web.config

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.webServer>
    <handlers>
      <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
    </handlers>
    <aspNetCore processPath="%LAUNCHER_PATH%" arguments="%LAUNCHER_ARGS%" forwardWindowsAuthToken="true" stdoutLogEnabled="true" />
  </system.webServer>
</configuration>

这是我的wwwroot web.config

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.webServer>
    <rewrite>
      <rules>
        <!--Redirect selected traffic to index -->
        <rule name="Index Rule" stopProcessing="true">
          <match url=".*" />
          <conditions logicalGrouping="MatchAll">
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
            <add input="{REQUEST_URI}" matchType="Pattern" pattern="^/api/" negate="true" />
            <add input="{REQUEST_URI}" matchType="Pattern" pattern="^/account/" negate="true" />
          </conditions>
          <action type="Rewrite" url="/index.html" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>
</configuration>

当我刷新一个有角度的2路线时,我从ASP.NET获得了一个 Status Code: 404; Not Found

3 回答

  • 4

    我找到史蒂夫桑德森的解决方案,似乎工作 . 他写了一篇关于RouteBuilder的扩展 . 您可以通过调用扩展方法MapSpaFallbackRoute在Setup.cs中对其进行配置

    https://github.com/aspnet/JavaScriptServices

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

    我找到了一个有效的解决方案here .

    下面是我的Configure方法中为我修复问题的代码 . 但要小心,申报令很重要 .

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    
        if (env.IsDevelopment()) {
            app.UseDeveloperExceptionPage();
        }
    
        app.Use(async (context, next) => {
            await next();
    
            if (context.Response.StatusCode == 404 && !Path.HasExtension(context.Request.Path.Value)) {
                context.Request.Path = "/";
                context.Response.StatusCode = 200;
                await next();
            }
        });
    
        app.UseDefaultFiles();
        app.UseStaticFiles();
    
        app.UseMvc(routes => {
            routes.MapRoute("Default", "api/{controller}/{action}/{id?}");
        });
    }
    
  • 0

    我有完全相同的问题 . 实际上,对我来说,当重写规则包含在web.config文件中时,IIS Express Server甚至没有启动 . 鉴于此,我在不依赖重写规则的情况下挖掘其他方式来做同样的事情 . 我发现你可以在startup.cs文件中使用MapWhen函数将MVC未处理的任何内容发送回index.html .

    在app.UseMvc()调用之后,以下代码已添加到Startup.cs类的Configure方法中 .

    app.UseMvc();
    
            // this serves "index.html" from the wwwroot folder when 
            // a route not containing a file extension is not handled by MVC.
            app.MapWhen(context =>
            {
                var path = context.Request.Path.Value.ToLower();
                return path.Contains(".");
            },
                branch =>
                {
                    branch.Use((context, next) =>
                    {
                        context.Request.Path = new PathString("/index.html");
                        return next();
                    });
    
                    branch.UseStaticFiles();
                });
    

    到目前为止,这看起来像它的工作,但我需要做更多的测试,看看是否有任何副作用 . 就个人而言,重写规则似乎是一个更好的解决方案,但这确实让我解决了这个问题 .

相关问题