- Modern Web Development with ASP.NET Core 3
- Ricardo Peres
- 267字
- 2021-06-18 18:35:59
Route data tokens
A route data token, as opposed to a route token or route parameter, is just some arbitrary data that you supply in a routing table entry and is available for use in the route handling pipeline, including the MVC action method. Unlike route tokens, route data tokens can be any kind of object, not just strings. They have absolutely no meaning for MVC, and will just be ignored, but they can be useful, because you can have multiple routes pointing to the same action method, and you may want to use data tokens to find out which route triggered the call.
You can pass a data token as follows:
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller}/{action}/{id?}",
defaults: new { controller = "Home", action = "Index" },
constraints: null,
dataTokens: new { foo = "bar" });
});
You can also retrieve them from the IDataTokensMetatata metadata item, as from inside a controller action:
public class HomeController : Controller
{
public IActionResult Index()
{
var metadata = this.HttpContext.GetEndpoint().Metadata.
GetMetadata<IDataTokensMetadata>();
var foo = metadata?.DataTokens["foo"] as string;
return this.View();
}
}
Because the DataTokens values are prototyped as object, you need to know what you will be retrieving. Also, be aware, the GetMetadata<IDataTokensMetadata>() method may return null if no data tokens were set!
There is no way to change the values of data tokens. Plus, the old RouteData property of the ControllerBase class and the GetRouteData extension method over HttpContext are now obsolete and may be removed in a future version of ASP.NET Core.
Finally, let's move on and see how we can configure routing to areas.
- Flask Web全棧開發實戰
- Google Flutter Mobile Development Quick Start Guide
- R語言經典實例(原書第2版)
- 深度學習經典案例解析:基于MATLAB
- jQuery EasyUI網站開發實戰
- Python自動化運維快速入門
- Learning Neo4j 3.x(Second Edition)
- 秒懂設計模式
- Internet of Things with Intel Galileo
- iOS應用逆向工程(第2版)
- 劍指Java:核心原理與應用實踐
- Visual Basic程序設計教程
- Hands-On Robotics Programming with C++
- Microsoft XNA 4.0 Game Development Cookbook
- Android開發權威指南(第二版)