asp.net-mvc – asp.NET:未知长度的MVC路径

前端之家收集整理的这篇文章主要介绍了asp.net-mvc – asp.NET:未知长度的MVC路径前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在asp.NET中为Web门户构建MVC应用程序.我准备了一系列控制器,并将所有不与之相关的路径映射到Page控制器,这将呈现适当的页面.

我的默认路由如下:

routes.MapRoute(
  "Default","{level1}/{level2}/{level3}",new { controller = "Page",action = "Index",level1 = "home",level2 = "",level3 = "" }
      );

但这有固定的宽度,它只接受最多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,Parms: company

或者有更好的方法对此进行建模吗?页面的所有路径都在数据库中,因此它们会动态更改.

解决方法

您可以使用通配符路由:
"{*data}"

看看这个SO:ASP.net MVC custom route handler/constraint

简单的解决方案:

(未经测试但……)

路线:

routes.Add(new Route
                           (
                           "{*data}",new RouteValueDictionary(new {controller = "Page",data = ""}),new PageRouteHandler()
                           )
                );

处理程序看起来像:

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);
    }
}
原文链接:https://www.f2er.com/aspnet/251364.html

猜你在找的asp.Net相关文章