本篇文章为大家展示了Route怎么在ASP.NET Core中使用,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。
创建 Controller 类
创建一个 DefaultController 类,新增如下代码。
public class DefaultController : Controller
{
[Route("")]
[Route("Default")]
[Route("Default/Index")]
public ActionResult Index()
{
return new EmptyResult();
}
[Route("Default/GetRecordsById/{id}")]
public ActionResult GetRecordsById(int id)
{
string str = string.Format
("The id passed as parameter is: {0}", id);
return Ok(str);
}
}
Route特性可用于 Controller 和 Action 级别,值得注意的是,如果应到到前者,那么 Controller 下的所有 Action 都受这个 Route 管控。
如果你仔细观察上面的 DefaultController 类代码,你会发现两个 Action 方法的 Route 路径都有 Default 前缀,这就不优雅了,优化方式就是把 Route 路径中的 Default 提取到 Controller 级别,代码如下:
[Route("Default")]
public class DefaultController : Controller
{
[Route("")]
[Route("Index")]
public ActionResult Index()
{
return new EmptyResult();
}
[HttpGet]
[Route("GetRecordsById/{id}")]
public ActionResult GetRecordsById(int id)
{
string str = string.Format("The id passed as parameter is: {0}", id);
return Ok(str);
}
}
可以看出当 Controller 和 Action 级别都被 Route 打上标记之后,Asp.Net Core 中的 Route 引擎会自动将两者拼接起来,当然更简单粗暴的做法就是在 Controller 上使用 RoutePrefix 特性,如下代码所示:
[RoutePrefix("services")]
public class HomeController : Controller
{
//Action methods
}
参考刚才的 DefaultController 类,我在 Index 方法上面定义了三个 Route 特性,这就意味着下面三种 Route 都可以访问到 Index() 方法,如下代码所示:
http://localhost:11277
http://localhost:11277/home
http://localhost:11277/home/index
常常在 基于约定 模式的Route中,它的 Route template 会有一些对参数的约定,比如下面的代码:
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
同样 基于特性 模式的 Route 也是可以使用参数模式的,比如文章之前的 DefaultController.GetRecordsById 就是的,值得注意的是模板中的 {id} 表示可接收任何参数,如 string,int 等等,如果你想限定为 int 的话,也是可以实现的。
Route 约束 就是 Controller 前的一个防火墙,他会踢掉一些不合规范的 Action 请求,比如说:你要求某个 Action 接收的参数必须是 int,那在 Route 模板中定义的语法格式一定是这样的 {parameter:constraint},如下代码所示:
[Route("Default/GetRecordsById/{id:int}")]
public ActionResult GetRecordsById(int id)
{
string str = string.Format("The id passed as parameter is: {0}", id);
return Ok(str);
}
你也可以在 Route Template 上指定可选参数,意味着这个参数可传可不传,格式如下:
[Route("Sales/GetSalesByRegionId/{id?}")]
有一点非常重要,当你使用了 Route特性 之后,其实 Controller 或者 Action 的名字就不再重要了,因为 Route处理引擎 已经不再将其作为参考选项,下面的代码片段展示了如何在 Action 方法上变更 Route template 格式。
[Route("Home/GetRecordsById/{id:int}")]
public ActionResult GetRecordsById(int id)
{
string str = string.Format("The id passed as parameter is: {0}", id);
return Ok(str);
}
接下来可以直接使用如下地址访问 GetRecordsById 方法。
http://localhost:11277/home/GetRecordsById/1
真实场景中你不仅要求 id 必须是整数,还要求必须有一定意义,比如说最小值为1,对这种有 多重约束 的需求如何去实现呢? 请看下面代码。
[Route("Default/GetRecordsById/{id:int:min(1)}")]
public ActionResult GetRecordsById(int id)
{
string str = string.Format("The id passed as parameter is: {0}", id);
return Ok(str);
}
int 限定为 int 类型
max/min 限定 int 的最大数和最小数
minlength 限定 string 的最小长度
regex 限定符合的正则
如果上面的一些约束不满足你的要求,你完全可以为你的场景深度定制,做法就是使用 IRouteConstraint 接口并实现它的 Match 方法即可,如下代码所示:
public class CustomRouteConstraint : IRouteConstraint
{
public bool Match(HttpContext httpContext, IRouter route,
string routeKey,
RouteValueDictionary values, RouteDirection routeDirection)
{
throw new NotImplementedException();
}
}
所谓的 token 占位符 就是具有一些特定含义的占位符号,比如说:[action], [area] 和 [controller],分别表示用你真实的 Controller 和 Action 去替换,下面的代码展示了如何使用这种模式去实现。
[Route("[controller]/[action]")]
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
public IActionResult Index()
{
return View();
}
//Other action methods
}
上述内容就是Route怎么在ASP.NET Core中使用,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。