Pal*_*tir 3 asp.net-mvc asp.net-mvc-routing
我正在asp.NET中为Web门户构建MVC应用程序.我准备了一系列控制器,并将所有不与之对应的路径映射到Page控制器,这将呈现适当的页面.
我的默认路由如下:
routes.MapRoute(
"Default",
"{level1}/{level2}/{level3}",
new { controller = "Page", action = "Index", level1 = "home", level2 = "", level3 = "" }
);
Run Code Online (Sandbox Code Playgroud)
但这有固定的宽度,它只接受最多3个级别.此外,我想管理附加到路径的操作,例如"编辑"和"删除".这可能吗?
company/about/who_we_are/staff -> Controller: Page, Action: Index, Parms: company/about/who_we_are/staff
company/about/who_we_are/staff/edit -> Controller: Page, Action: Edit, Parms: company/about/who_we_are/staff
company/edit -> Controller: Page, Action: Edit, Parms: company
Run Code Online (Sandbox Code Playgroud)
或者有更好的方法对此进行建模吗?页面的所有路径都在数据库中,因此它们会动态更改.
您可以使用通配符路由:
"{*data}"
Run Code Online (Sandbox Code Playgroud)
看看这个SO:ASP.net MVC自定义路由处理程序/约束
(未经测试但......)
路线:
routes.Add(new Route
(
"{*data}",
new RouteValueDictionary(new {controller = "Page", action = "Index", data = ""}),
new PageRouteHandler()
)
);
Run Code Online (Sandbox Code Playgroud)
处理程序看起来像:
public class PageRouteHandler : IRouteHandler
{
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
return new PageHttpHandler(requestContext);
}
}
class PageHttpHandler : MvcHandler
{
public PageHttpHandler(RequestContext requestContext)
: base(requestContext)
{
}
protected override void ProcessRequest(HttpContextBase httpContext)
{
IController controller = new PageController();
((Controller)controller).ActionInvoker = new PageActionInvoker();
controller.Execute(RequestContext);
}
}
class PageActionInvoker : ControllerActionInvoker
{
protected override ActionResult InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary<string, object> parameters)
{
string data = controllerContext.RouteData.GetRequiredString("data");
string[] tokens = data.Split('/');
int lenght = tokens.Length;
if (lenght == 0)
return new NotFoundResult();
if (tokens[tokens.Length - 1] == "edit")
{
parameters["action"] = "edit";
lenght--;
}
for (int i = 0; i < length; i++)
parameters["level" + (i + 1).ToString()] = tokens[i];
return base.InvokeActionMethod(controllerContext, actionDescriptor, parameters);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
838 次 |
| 最近记录: |