- 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.
- jQuery Mobile Web Development Essentials(Third Edition)
- 深入理解Bootstrap
- GraphQL學習指南
- Building a Home Security System with Raspberry Pi
- C++面向對象程序設計(微課版)
- Python從菜鳥到高手(第2版)
- Spring Boot+Spring Cloud+Vue+Element項目實戰:手把手教你開發權限管理系統
- SQL經典實例(第2版)
- Java網絡編程實戰
- Learning PHP 7
- Learning Modular Java Programming
- Buildbox 2.x Game Development
- Hands-On JavaScript for Python Developers
- 深入實踐Kotlin元編程
- Python機器學習算法與應用