我正在将我的项目升级到 ASPNET5。我的应用程序是一个 AngularJS Web 应用程序,它使用 HTML5 Url 路由(HTML5 历史 API https://developer.mozilla.org/en-US/docs/Web/API/History ).
在我之前的应用程序中,我使用了 URL 重写 IIS 模块,其代码如下:
<system.webServer>
<rewrite>
<rules>
<rule name="MainRule" stopProcessing="true">
<match url=".*" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
<add input="{REQUEST_URI}" matchType="Pattern" pattern="api/(.*)" negate="true" />
<add input="{REQUEST_URI}" matchType="Pattern" pattern="signalr/(.*)" negate="true" />
</conditions>
<action type="Rewrite" url="Default.cshtml" />
</rule>
</rules>
</rewrite>
<system.webServer>
我意识到我可以移植它,但我想最小化我的 Windows 依赖性。根据我的阅读,我认为我应该能够使用 ASP.NET 5 中间件来完成此任务。
我认为代码看起来像这样,但我认为我还很遥远。
app.UseFileServer(new FileServerOptions
{
EnableDefaultFiles = true,
EnableDirectoryBrowsing = true
});
app.Use(async (context, next) =>
{
if (context.Request.Path.HasValue && context.Request.Path.Value.Contains("api"))
{
await next();
}
else
{
var redirect = "http://" + context.Request.Host.Value;// + context.Request.Path.Value;
context.Response.Redirect(redirect);
}
});
本质上,我想路由任何包含/api
or /signalr
。关于在 ASPNET5 中实现此目的的最佳方法有什么建议吗?
您走在正确的轨道上,但我们不想发回重定向,而是想重写请求上的路径。以下代码从 ASP.NET5 RC1 开始运行。
app.UseIISPlatformHandler();
// This stuff should be routed to angular
var angularRoutes = new[] {"/new", "/detail"};
app.Use(async (context, next) =>
{
// If the request matches one of those paths, change it.
// This needs to happen before UseDefaultFiles.
if (context.Request.Path.HasValue &&
null !=
angularRoutes.FirstOrDefault(
(ar) => context.Request.Path.Value.StartsWith(ar, StringComparison.OrdinalIgnoreCase)))
{
context.Request.Path = new PathString("/");
}
await next();
});
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseMvc();
这里的一个问题是,您必须将角度路线专门编码到中间件中(或将它们放入配置文件等中)。
最初,我尝试创建一个管道afterUseDefaultFiles() 和 UseStaticFiles() 已被调用,它将检查路径,如果路径不是 /api,则重写它并将其发送回(因为 /api 以外的任何内容都应该已经被处理)。然而,我永远无法让它发挥作用。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)