我正在将我的项目升级到 ASPNET5。我的应用程序是一个使用 HTML5 Url 路由 (HTML5 History API) 的 AngularJS Web 应用程序。
在我以前的应用程序中,我使用了 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
或 /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();
这里的一个问题是您必须将角度路由专门编码到中间件中(或将它们放入配置文件等)。
最初,我尝试创建一个管道,其中 在 UseDefaultFiles() 和 UseStaticFiles() 被调用后,它会检查路径,如果路径不是/api,重写它并发送它返回(因为/api 以外的任何东西都应该已经处理过了)。但是,我永远无法让它发挥作用。
关于ASP.NET 5 HTML5 历史,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31184446/