在尝试隐藏控制器时,ActionLink会将控制器参数添加到链接

时间:2013-03-10 19:12:00

标签: asp.net-mvc

我想根据组的值来制作控制器,所以我有以下路线:

routes.MapRoute(
     name: "Default",
     url: "{group}/{action}",
     defaults: new { group = "Default", action = "Index" }
).RouteHandler = new MyRouteHandler();

使用以下routehandler和httphandler:

public class MyRouteHandler : IRouteHandler
{
    public IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        return new MyHttpHandler(requestContext);
    }
}

public class MyHttpHandler : IHttpHandler
{
    RequestContext _requestContext;

    public MyHttpHandler(RequestContext requestContext)
    {
        _requestContext = requestContext;
    }

    public bool IsReusable
    {
        get { return true; }
    }

    public void ProcessRequest(HttpContext context)
    {
        var groupName = _requestContext.RouteData.GetRequiredString("group");

        // Select the controller, e.g. Home:

        _requestContext.RouteData.Values.Add("controller", "Home");

        IControllerFactory factory = ControllerBuilder.Current.GetControllerFactory();
        IController controller = factory.CreateController(_requestContext, "Home");
        if (controller != null)
        {
            controller.Execute(_requestContext);
        }
    }
}

这一切都有效但如果在页面上放置一个@ Html.ActionLink(“索引”,“索引”),则会产生以下链接:

[a href =“/?controller = Home”]索引[/ a]

有人可以告诉我为什么在使用Html.ActionLink时添加了控制器参数? (我不想添加添加到链接的controller = Home参数。)

非常感谢!

1 个答案:

答案 0 :(得分:0)

可能的解决方案

routes.MapRoute(
   name: "Default",
   url: "{group}/{action}/{controller}",
   defaults: new { group = "Default", action = "Index", controller = "Home" }
);

@Html.ActionLink("Index", "Index", new {group = "Group"});