允许 OWIN 在刷新时重定向我的 angularjs 虚拟路径

Allow OWIN to redirect my angularjs virtual path when refreshing

我目前正在 visual studio 中进行调试,因此我的网站由 IIS Express 托管。

在我的应用程序中,如果我通过 angular 转到 /login,它可以正常工作并加载我的部分页面。但是,如果我刷新页面,则会收到 404 错误。即使尝试设置 app.Map 将我的路线修改回 index.cshtml,它也不起作用。

    app.Map("/login", (map) =>
    {
        map.Use(
            async (context, next) =>
            {
                //...
            });
    });

响应代码很好,200,但 IIS 仍然给出 404 错误。

我的最终目标是能够保存我的 ui-路由器路径的状态,这样我就可以将它添加为书签并返回到它,服务器重定向回我的 angular 应用程序并且应用程序导航到正确的状态。

我到底要怎么做才能做到这一点?我不想做任何 IIS 配置,因为我什至可能不会使用 IIS。

我想使用的另一个选项是让服务器发回散列 url,例如 /#/login,但它似乎不允许这样做。 OWIN 似乎总是将哈希解析为 %23,我似乎无法绕过它。

将此添加到您的 web.config。这是 IIS 中的重写模块:

<configuration>
    <system.webServer>
        <rewrite>
          <rules>
            <rule name="Main Rule" stopProcessing="true">
                    <match url=".*" />
                    <conditions logicalGrouping="MatchAll">
                        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
                        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
                    </conditions>
                    <action type="Rewrite" url="/" />
                </rule>
            </rules>
        </rewrite>
    </system.webServer>
</configuration>

Source

这可以完全在 OWIN 中解决,方法是使用中间件重写请求。

public async override Task Invoke(IOwinContext context)
{           
    if(!Path.HasExtension(context.Request.Path.Value))
    {
        context.Request.Path = new PathString("/");
    }
    await _next.Invoke(context);
}

请注意,如果您也是同一应用程序中的 运行 WebAPI 端点,那么您可能需要将它们的路径排除在重写之外。