问题

如何在ASP.NET Core 2.0中由路由引擎来生成网址?

答案

新建一个空项目,修改Startup.cs文件,添加MVC服务和中间件:

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?}");
});
}

  

添加一个MobileController控制器类:

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]
public IActionResult PageTwo()
{
var url = Url.Action("PageTwo"); // /mobile/PageTwo OR /mobile/PageTwo/1?
return Content($"(GET) Mobile/Two (Url: {url})");
} [HttpPost]
public IActionResult PageTwo(int id)
{
var url = Url.Action("PageTwo"); // /mobile/PageTwo/1
return Content($"(POST) Mobile/Two: {id} (Url: {url})");
} public IActionResult PageThree()
{
var url = Url.RouteUrl("goto_two", new { id = 5 }); // /two/5
return Content($"Mobile/Three (Url: {url})");
} public IActionResult PageFour()
{
var url = Url.RouteUrl("goto_two", new { q = 5 }); // /two?q=5
return Content($"Mobile/Four (Url: {url})");
} public IActionResult PageFive()
{
return RedirectToAction("PageSix");
} public IActionResult PageSix()
{
return Content("Mobile/Six (Mobile/Five will also come here)");
}
}

讨论

我们可以使用MVC的路由机制来生成网址,而无需在应用程序中硬编码网址。MVC有这么做的所有信息,来自于我们设置路由映射所提供的模板。

MVC提供了IUrlHelper接口来提供生成网址的功能。这是通过在控制器基类,视图和试图组件公开Url属性来实现的。

IUrlHelper接口提供两个关键的方法来生成网址:

  1. Action:通过提供控制器,方法和路由参数值来生成网址。
  2. RouteUrl: 通过提供路由映射名称和路由参数来生成网址。

如果调用上述方法时未提供控制器和路由参数,那么MVC会从当前请求或者方法参数中获取(即是从当前上下文的环境变量中获取)。下面的方法存在于MobileController控制器中:

public IActionResult PageTwo(int id)
{
var url = Url.Action("PageTwo"); // /mobile/PageTwo/1
return Content($"(POST) Mobile/Two: {id} (Url: {url})");
}  

路由参数可以作为匿名对象来提供:

public IActionResult PageThree()
{
var url = Url.RouteUrl("goto_two", new { id = 5 }); // /two/5
return Content($"Mobile/Three (Url: {url})");
}

如果MVC无法将这些值映射到地址标记,那么这些参数会作为网址的查询字符串拼接起来:

public IActionResult PageFour()
{
var url = Url.RouteUrl("goto_two", new { id=5, key1 = "value1" }); // /two/5?key1=value1
return Content($"Mobile/Four (Url: {url})");
}

ControlBase类上有一个很方便的方法RedirectToAction,用来将用户请求重定向到某个控制器方法中,这一过程是在客户端完成的:

public IActionResult PageFive()
{
return RedirectToAction("PageSix");
} public IActionResult PageSix()
{
return Content("Mobile/Six (Mobile/Five will also come here)");
}

  

为了将IUrlHeper作为依赖项注入需要的类中,我们需要首先在ConfigureServices中配置相应的服务:

public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();
services.AddScoped<IUrlHelper>(factory =>
{
var actionContext = factory.GetService<IActionContextAccessor>().ActionContext;
return new UrlHelper(actionContext);
}); services.AddMvc();
}  

注:大部分情况下我们无需通过注入来使用IUrlHelper,因为控制器,视图中都已经公开了Url属性供我们使用。

源代码下载

原文:https://tahirnaushad.com/2017/08/20/asp-net-core-mvc-routing/

[译]ASP.NET Core 2.0 路由引擎之网址生成的更多相关文章

  1. [译]ASP.NET Core 2.0 路由引擎

    问题 ASP.NET Core 2.0的路由引擎是如何工作的? 答案 创建一个空项目,为Startup类添加MVC服务和请求中间件: public void ConfigureServices(ISe ...

  2. [译]ASP.NET Core 2.0 视图引擎

    问题 如何在ASP.NET Core 2.0中使用Razor引擎来创建视图? 答案 新建一个空项目,修改Startup.cs,添加MVC服务和请求中间件: public void ConfigureS ...

  3. [译]ASP.NET Core 2.0 系列文章目录

    基础篇 [译]ASP.NET Core 2.0 中间件 [译]ASP.NET Core 2.0 带初始参数的中间件 [译]ASP.NET Core 2.0 依赖注入 [译]ASP.NET Core 2 ...

  4. [译]ASP.NET Core 2.0 部分视图

    问题 如何在ASP.NET Core 2.0中使用部分视图来重用页面的公共部分? 答案 新建一个空项目,在Startup中添加MVC服务和中间件: public void ConfigureServi ...

  5. [译]ASP.NET Core 2.0 区域

    问题 如何将一个规模庞大的ASP.NET Core 2.0应用程序进行逻辑分组? 答案 新建一个ASP.NET Core 2.0空项目,修改Startup类,增加Mvc服务和中间件: public v ...

  6. [译]ASP.NET Core 2.0 中间件

    问题 如何创建一个最简单的ASP.NET Core中间件? 答案 使用VS创建一个ASP.NET Core 2.0的空项目,注意Startup.cs中的Configure()方法: public vo ...

  7. [译]ASP.NET Core 2.0 带初始参数的中间件

    问题 如何在ASP.NET Core 2.0向中间件传入初始参数? 答案 在一个空项目中,创建一个POCO(Plain Old CLR Object)来保存中间件所需的参数: public class ...

  8. [译]ASP.NET Core 2.0 全局配置项

    问题 如何在 ASP.NET Core 2.0 应用程序中读取全局配置项? 答案 首先新建一个空项目,并添加两个配置文件: 1. appsettings.json { "Section1&q ...

  9. [译]ASP.NET Core 2.0 机密配置项

    问题 如何在ASP.NET Core 2.0中保存机密配置项(不用将其暴露给源代码管理器)? 答案 创建一个ASP.NET Core 2.0空项目,在项目节点上点击右键,并点击菜单项 - 管理用户机密 ...

随机推荐

  1. 学习OpenResty的正确姿势

    前段时间老罗退出得到专栏事情闹得沸沸扬扬,另一位老罗也给出了合理的会员退费,感觉得到还是蛮贴心的.想想也是,毕竟精力有限,如今老罗也有了十亿的投资,集中精力做好手机才是主业.记得老罗刚开专栏那段时间很 ...

  2. ACM学习之路___HDU 1385(带路径保存的 Floyd)

    Description These are N cities in Spring country. Between each pair of cities there may be one trans ...

  3. StringBuffer和String的相互转换

    1:用法: * A:String -- >StringBuffer * a:通过构造方法 * b:通过append()方法 * B:StringBuffer --> String * a: ...

  4. 实例讲解webpack的基本使用第三篇

    这一篇来讲解一下webpack的htmlWebpackHtml插件的使用. 先来思考一个实际问题:我们现在在index.html引用的js文件是写死的.但是我们每次打包后的文件都是动态的,那么我们怎么 ...

  5. asp.net web api 2.2 基础框架(带例子)

    链接:https://github.com/solenovex/asp.net-web-api-2.2-starter-template 简介 这个是我自己编写的asp.net web api 2.2 ...

  6. 用 Python 撸一个区块链

    本文翻译自 Daniel van Flymen 的文章 Learn Blockchains by Building One 略有删改.原文地址:https://hackernoon.com/learn ...

  7. JavaWeb(一)Servlet中的request与response

    一.HttpServletRequest概述 1.1.HttpServletRequest简介 HttpServletRequest对象代表客户端的请求,当客户端通过HTTP协议访问服务器时,HTTP ...

  8. WebApi接口返回json,xml,text纯文本等

    [Route("api/Message/MessageList/")] [HttpGet] public HttpResponseMessage MessageList() { R ...

  9. Go 单例模式[个人翻译]

    原文地址:http://marcio.io/2015/07/singleton-pattern-in-go/ 最近几年go语言的增长速度非常惊人,吸引着各界人士切换到Go语言.最近有很多关于使用Rub ...

  10. Xamarin Forms 进度条控件

    本文翻译:http://xamlnative.com/2016/04/14/xamarin-forms-a-simple-circular-progress-control/ 里面都是胡说的,如果看不 ...