1

Is there a way in ASP.NET MVC 4 to bind route values from sources other than a placeholder in a route URL: a header or post data for example? Or are they intrinsically coupled to the URL?

Specifically, I was interested in overriding the action route value with a value from a posted form field. That way, you could easily have different submit buttons on a page that invoked different actions on the controller by giving each a name of action and a value of the action name.

I've tried setting the RouteData.Values in an HttpModule but that appears to be too early in the pipeline to override the action.

4

1 回答 1

1

HttpModule这确实为时过早,实际上是不需要的。您可以依赖常规的 MVC 路由处理机制,并简单地为它提供您自己RouteValues从 HTTP 请求中提取的内容。

例如:

public class MyHeadersBasedRoute : RouteBase
{
    public const string HEADER_CONTROLLER_KEY = "X-REQUESTED-CONTROLLER";
    public const string HEADER_ACTION_KEY = "X-REQUESTED-ACTION";

    public override RouteData GetRouteData(HttpContextBase httpContext)
    {
        var requestedController = httpContext.Request.Headers[HEADER_CONTROLLER_KEY];
        var requestedAction = httpContext.Request.Headers[HEADER_ACTION_KEY];

        if (String.IsNullOrEmpty(requestedController) || String.IsNullOrEmpty(requestedAction))
            return null;

        var ret = new RouteData(this, new MvcRouteHandler());

        ret.Values.Add("controller", requestedController);
        ret.Values.Add("action", requestedAction);

        // add any extra parameter from request, for example:
        ret.Values.Add("id", httpContext.Request.Form["id"]);

        return ret;
    }

    public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
    {
        return null;
    }
}

然后只需将其注册到您的global.asax

 RouteTable.Routes.Add(new MyHeadersBasedRoute());
于 2013-06-26T09:53:43.060 回答