Azr*_*ria 5 c# asp.net-mvc asp.net-mvc-routing
默认情况下,MVC中的URL路由是{controller}/{action}/{id}.然后我们可以访问mydomain.com/Products/Details/1等.
现在,我已经注册了另一个名为CategoryLandingPage的地图路线.
routes.MapRoute(
name: "CategoryLandingPage",
url: "category",
defaults: new { controller = "Category", action = "Index" });
Run Code Online (Sandbox Code Playgroud)
因此它将显示页面中的所有类别.
然后我注册另一个名为CategoryDetails的地图路线
routes.MapRoute(
name: "CategoryDetails",
url: "category/{categoryName}",
defaults: new { controller = "Category", action = "Details", categoryName = UrlParameter.Optional });
Run Code Online (Sandbox Code Playgroud)
当有人访问mydomain.com/category/cars时,它将显示与汽车相关的所有产品.
同一个控制器还有另一个操作,如创建,编辑,删除等.
问题是,当我访问mydomain.com/category/create时,它将转到Details操作.它不会转到类别控制器中的创建操作.
我怎么能解决这个问题呢?
两种方式:
使用路由约束来确保 {categoryName} 部分与您的类别之一匹配:
//You will have to make this
var categoryRouteConstraint = new CategoryRouteConstraint();
routes.MapRoute(
name: "CategoryDetails",
url: "category/{categoryName}",
constraints: new { categoryName = categoryRouteConstraint }
defaults: new { controller = "Category", action = "Details", categoryName = UrlParameter.Optional });
Run Code Online (Sandbox Code Playgroud)
路线约束示例:
public class CategoryRouteConstraint : IRouteConstraint
{
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
if (routeDirection == RouteDirection.UrlGeneration)
return true;
if (string.Equals(parameterName, "categoryName", StringComparison.OrdinalIgnoreCase))
{
//return true if (string)values[parameterName] == "known category name"
}
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
或者,先拦截具体动作:
routes.MapRoute(
name: "CategoryDetails",
url: "category/create",
defaults: new { controller = "Category", action = "Create", categoryName = UrlParameter.Optional });
routes.MapRoute(
name: "CategoryDetails",
url: "category/delete",
defaults: new { controller = "Category", action = "Delete", categoryName = UrlParameter.Optional });
//Do one for Edit, Delete
//CategoryDetails route after
routes.MapRoute(
name: "CategoryDetails",
url: "category/{categoryName}",
defaults: new { controller = "Category", action = "Details", categoryName = UrlParameter.Optional });
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
106 次 |
| 最近记录: |