如何从变量中的url获取动作名称,而不是从routedata获取动作名称

时间:2013-07-08 07:41:53

标签: asp.net-mvc

我在变量中有url(所以我不能使用RouteData.Values [“action”]):

string url = "/aaaa/bbb?c=5";

如何在变量??

中从此url获取操作名称

1 个答案:

答案 0 :(得分:1)

如果您使用的是实际网址,请使用提供函数application path作为HttpRequest前置string url = GetApplicationPath(HttpContext.Request) + "/aaaa/bbb?c=5"; var request = new HttpRequest(null, url, ""); var response = new HttpResponse(new StringWriter()); var httpContext = new HttpContext(request, response); var routeData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(httpContext)); var values = routeData.Values; var controller = values["controller"]; //aaaa var action = values["action"]; //bbb 需要完整路径

Global.asax

控制器和操作的值将取决于routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults ); 中的路线设置,如果您有以下设置

var controller = values["controller"]; //aaaa
var action = values["action"]; //bbb

输出

routes.MapRoute(
    "Default", // Route name
    "{action}/{controller}/{id}", // URL with parameters
    new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);

但是你设置为

var controller = values["controller"]; //bbb
var action = values["action"]; //aaaa

输出

private string GetApplicationPath(HttpRequestBase request)
{
    var path = request.Url.Scheme + "://" + request.Url.Host;
    if (request.ApplicationPath != @"/")
    {
        path += request.ApplicationPath;
    }
    if (!path.EndsWith(@"/"))
    {
        path += "/";
    }
    return path;
}

添加效用函数功能

{{1}}