官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 台安县| 迁安市| 攀枝花市| 石阡县| 天柱县| 博白县| 五莲县| 安阳市| 海伦市| 鲜城| 民县| 深水埗区| 乳山市| 同德县| 故城县| 巴南区| 东山县| 饶阳县| 泰宁县| 莎车县| 江安县| 胶南市| 正定县| 珠海市| 石泉县| 乌鲁木齐县| 灵山县| 永宁县| 将乐县| 共和县| 且末县| 嘉荫县| 武邑县| 台北市| 油尖旺区| 昌平区| 巴马| 碌曲县| 手游| 临洮县| 梅州市|