【发布时间】:2018-05-22 07:23:07
【问题描述】:
以前在 ASP.NET MVC 中
<routes>
<add name="VehicleDetailRoute" url="TwoWheeler/VehicleDetail/{id}">
<defaults controller="Integration" action="VehicleDetail" id="Optional" />
</add>
</routes>
public void RegisterRoutes(RouteCollection routes)
{ //Fill the route table section
RouteSection routesTableSection = GetRouteTableConfigurationSection();
if (routesTableSection == null || routesTableSection.Routes.Count <= 0)
return;
for (int routeIndex = 0; routeIndex < routesTableSection.Routes.Count; routeIndex++)
{
//base on different route, we have created dynamic routes and add in to
var routeElement = routesTableSection.Routes[routeIndex];
var route = new Route(
routeElement.Url,
GetDefaults(routeElement),
GetConstraints(routeElement),
GetDataTokens(routeElement),
GetInstanceOfRouteHandler(routeElement));
routes.Add(routeElement.Name, route);
}
}
在这里,客户在浏览器上看到 TwoWheeler/VehicleDetail/,但在内部它将控制器视为 Integration,将操作视为“VehicleDetail”
现在在 .Net Core 中,我们创建了 JSON 文件并希望读取。 (希望从 ASP.NET MVC 迁移到 .Net Core 2.0)。 您可以根据需要更改格式或 JSON。
{
"routes": {
"VehicleDetailRoute": {
"url": "TwoWheeler/VehicleDetail/{id}",
"controller": "Integration",
"action": "VehicleDetail",
"id": "Optional"
}
}
}
- url : 在浏览器上显示
- 控制器:原始控制器
- 动作:原始动作
- VehicleDetailRoute:路线名称
到目前为止,我已经阅读了 Startup 文件中的配置
public Startup(IConfiguration configuration)
{
var configurationBuilder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("routes.json", optional: false, reloadOnChange: true);
Configuration = configurationBuilder.Build();
}
在ConfigureServices
中添加了services.AddRouting();
在配置方法中,添加app.UseStaticFiles();
构建路由
var routeBuilder = new RouteBuilder(app);
routeBuilder.MapGet("{route}", context =>
{
var routeMessage = Configuration.AsEnumerable()
.FirstOrDefault(r => r.Key == context.GetRouteValue("route")
.ToString())
.Value;
var defaultMessage = Configuration.AsEnumerable()
.FirstOrDefault(r => r.Key == "default")
.Value;
var response = (routeMessage != null) ? routeMessage : defaultMessage;
return context.Response.WriteAsync(response);
});
app.UseRouter(routeBuilder.Build());
问题:根据客户输入的 URL,我想重定向特定操作。想用动态输入执行下面的方法
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Integration}/{action=VehicleDetailOnline}/{id?}");
});
检查以下参考:radu-matei.com -- c-sharpcorner -- StackOverflow
【问题讨论】:
-
有什么东西阻止你使用属性路由?
标签: c# .net asp.net-core asp.net-core-mvc asp.net-core-2.0