ASP.NET Core 2.0 路由引擎:网址生成攻略(译)

0 下载量 3 浏览量 更新于2024-08-31 收藏 57KB PDF 举报
"ASP.NET Core 2.0 路由引擎之网址生成" 在ASP.NET Core 2.0中,路由引擎是应用的核心组件之一,它负责解析HTTP请求并将其映射到相应的处理方法(如控制器的动作)。同时,路由引擎还提供了一种机制来生成网址,这对于创建链接和重定向非常有用。本文将详细讲解如何在ASP.NET Core 2.0中利用路由引擎生成网址。 首先,在`Startup.cs`文件中,我们需要配置MVC服务和中间件。在`ConfigureServices`方法中,我们通过调用`AddMvc()`添加MVC服务。接着,在`Configure`方法中,我们使用`UseMvc()`中间件,并传入一个配置路由的委托,这样可以定义应用程序的路由规则。 ```csharp public void ConfigureServices(IServiceCollection services) { services.AddMvc(); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseMvc(routes => { routes.MapRoute( name: "goto_one", template: "one", defaults: new { controller = "Home", action = "PageOne" }); routes.MapRoute( name: "goto_two", template: "two/{id?}", defaults: new { controller = "Home", action = "PageTwo" }); routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); } ``` 这里定义了三个路由模板: 1. `goto_one`:匹配URL "one",默认指向`Home`控制器的`PageOne`动作。 2. `goto_two`:匹配URL "two/id",其中"id"是可选参数,同样映射到`Home`控制器的`PageTwo`动作。 3. `default`:这是默认路由,如果其他路由都不匹配,会尝试这个,它允许URL以任意控制器和动作名开始,如 "Home/Index"。 接下来,为了演示如何生成网址,我们创建一个名为`MobileController`的控制器: ```csharp public class MobileController : Controller { public IActionResult Index() { var url = Url.Action("Index"); // /mobile return Content($"Mobile/Index(Url:{url})"); } public IActionResult PageOne() { var url = Url.Action("PageOne"); // /mobile/PageOne return Content($"Mobile/One(Url:{url})"); } [HttpGet("/mobile/PageTwo/{id}")] public IActionResult PageTwo(string id) { var url = Url.Action("PageTwo", new { id }); // /mobile/PageTwo/someValue return Content($"Mobile/Two(Url:{url}, Id:{id})"); } } ``` 在`MobileController`中,我们可以看到几个动作方法,每个方法都使用`Url.Action`方法来生成网址。`Url.Action`接受两个参数:一个是动作名称,另一个是包含任何必要路由值的对象。例如,在`PageOne`方法中,`Url.Action("PageOne")`将返回"/mobile/PageOne",因为它匹配了我们在`Configure`方法中定义的路由规则。 在`PageTwo`方法中,我们通过传递`id`参数来生成包含特定值的URL。这使得`Url.Action`能够生成如"/mobile/PageTwo/someValue"这样的URL。 总结来说,ASP.NET Core 2.0的路由引擎提供了灵活的网址生成能力,可以通过`Url.Action`方法轻松地在控制器中创建指向其他动作或控制器的链接。这在构建动态Web应用时非常有用,特别是在处理导航、重定向和生成HTML链接时。通过理解路由规则和`Url.Action`的工作方式,开发者可以更好地控制应用程序的URL结构,提升用户体验。