amc*_*dnl 8 .net asp.net html5 asp.net-web-api-routing asp.net-core
我正在将我的项目升级到ASPNET5.我的应用程序是使用HTML5 URL路由(HTML5历史记录API)的AngularJS Web App .
在我以前的应用程序中,我使用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>
Run Code Online (Sandbox Code Playgroud)
我意识到我可以移植它,但我想最小化我的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);
}
});
Run Code Online (Sandbox Code Playgroud)
基本上,我想要路由任何包含/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();
Run Code Online (Sandbox Code Playgroud)
这里的一个问题是您必须将角度路由专门编码到中间件中(或将它们放在配置文件中等)。
最初,我尝试创建一个管道,在调用 UseDefaultFiles() 和 UseStaticFiles() 之后,它会检查路径,如果路径不是 /api,则重写它并将其发送回(因为除 /api 之外的任何内容都应该已经处理了)。但是,我永远无法让它发挥作用。
小智 -2
为什么不在 MVC 中使用路由功能?在Startup.cs的Configure方法中,您可以修改以下内容:
// inside Configure method in Startup.cs
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action}/{id?}",
defaults: new { controller = "Home", action = "Index" });
// Uncomment the following line to add a route for porting Web API 2 controllers.
// routes.MapWebApiRoute("DefaultApi", "api/{controller}/{id?}");
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1560 次 |
| 最近记录: |