【发布时间】:2015-03-04 04:07:06
【问题描述】:
我有一个 ASP.NET MVC 应用程序。我正在学习 ASP.NET vNext。为此,我决定将我现有的应用程序移植到 vNext。我不确定的是,如何移植我的路线。
在我的原始 ASP.NET MVC 应用程序中,我有以下内容:
RouteConfig.cs
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.RouteExistingFiles = true;
routes.MapRoute(
name: "Index",
url: "",
defaults: new { controller = "Root", action = "Index" }
);
routes.MapRoute(
name: "Items",
url: "items/{resource}",
defaults: new { controller = "Root", action = "Items", resource = UrlParameter.Optional }
);
routes.MapRoute(
name: "BitcoinIntegration",
url: "items/available/today/{location}",
defaults: new { controller="Root", action="Availability", location=UrlParameter.Optional }
);
routes.MapRoute(
name: "BlogPost1",
url: "about/blog/the-title",
defaults: new { controller = "Root", action = "BlogPost1" }
);
}
现在在这个 ASP.NET vNext 世界中,我不确定如何设置路由。我有以下内容:
Startup.cs
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Routing;
using Microsoft.Framework.DependencyInjection;
namespace MyProject.Web
{
public class Startup
{
public void Configure(IApplicationBuilder app)
{
app.UseErrorPage();
app.UseServices(services =>
{
services.AddMvc();
});
app.UseMvc(routes =>
{
routes.MapRoute("areaRoute", "{area:exists}/{controller}/{action}");
});
app.UseMvc();
app.UseWelcomePage();
}
}
}
不过,我不确定两件事:
- 如何添加我之前在 RouteConfig.cs 中定义的路由。
- 如何使用
views/home/Index.cshtml代替app.UseWelcomePage()作为我的默认路径。
【问题讨论】:
-
app.UseMvc(routes => RouteConfig.RegisterRoutes(routes))有什么问题?这不是 vNext 的区别,它只是常规的 MVC,除了您使用 OWIN 引导您的应用程序而不是在 Global.asax 中显式注册您的路线。路由的工作原理相同,您只是从不同的地方调用RegisterRoutes。至于您的其他 Home/Index 问题,只需删除对UseWelcomePage的调用 - 您的路由将执行它本来会执行的操作。 -
@AntP - vNext 中是否有更“推荐”的方法?我试图尽可能地与 vNext 保持一致,以便我以正确的方式学习它。谢谢。
-
您仍然需要在传递给
UseMvc的委托中包含您的路由 - 无论您是否在其中调用RouteConfig.RegisterRoutes(routes)或只是声明一个匿名委托并在那里添加所有路由代码(就像在您当前的示例中一样)实际上几乎没有什么区别。我可能会将其保留在RouteConfig中,但只是为了避免使Configure方法膨胀。 vNext 约定只是规定您使用 OWIN 引导您的应用程序(而不是使用Global.asax方法),您已经在这样做了。