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

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.

主站蜘蛛池模板: 乌拉特后旗| 兴海县| 广州市| 县级市| 灵宝市| 米林县| 五常市| 武义县| 京山县| 台北县| 南京市| 济南市| 耒阳市| 游戏| 阜宁县| 文化| 高碑店市| 许昌县| 察隅县| 贡嘎县| 红安县| 嵊泗县| 吉林省| 利川市| 明水县| 常山县| 瓦房店市| 乐东| 民乐县| 康马县| 九龙城区| 山阳县| 襄樊市| 平原县| 双辽市| 巴青县| 于都县| 新巴尔虎右旗| 黄浦区| 舞阳县| 习水县|