1

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

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

如何从变量中的此 url 获取操作名称?

4

1 回答 1

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;
}
于 2013-07-08T08:08:52.743 回答