如何从Referrer Uri获取Controller和Action名称?

dea*_*_au 31 c# razor asp.net-mvc-3

从控制器和动作名称构建Uris有很多信息,但是我怎么能这样做呢?

基本上,我想要实现的是从引用页面获取Controller和Action名称(即Request.UrlReferrer).有没有一种简单的方法来实现这一目标?

gdo*_*ica 53

我认为这应该可以解决问题:

// Split the url to url + query string
var fullUrl = Request.UrlReferrer.ToString();
var questionMarkIndex = fullUrl.IndexOf('?');
string queryString = null;
string url = fullUrl;
if (questionMarkIndex != -1) // There is a QueryString
{    
    url = fullUrl.Substring(0, questionMarkIndex); 
    queryString = fullUrl.Substring(questionMarkIndex + 1);
}   

// Arranges
var request = new HttpRequest(null, url, queryString);
var response = new HttpResponse(new StringWriter());
var httpContext = new HttpContext(request, response)

var routeData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(httpContext));

// Extract the data    
var values = routeData.Values;
var controllerName = values["controller"];
var actionName = values["action"];
var areaName = values["area"];
Run Code Online (Sandbox Code Playgroud)

我的Visual Studio目前已关闭,因此我无法测试它,但它应该按预期工作.

  • 您可能想稍微编辑此代码.如果你的引用者没有查询字符串,你最终会尝试调​​用fullUrl.Substring(0,-1). (2认同)

Joe*_*der 5

为了扩展 gdoron 的答案,Uri该类提供了无需进行字符串解析即可获取 URL 左右部分的方法:

url = Request.UrlReferrer.GetLeftPart(UriPartial.Path);
querystring = Request.UrlReferrer.Query.Length > 0 ? uri.Query.Substring(1) : string.Empty;

// Arranges
var request = new HttpRequest(null, url, queryString);
var response = new HttpResponse(new StringWriter());
var httpContext = new HttpContext(request, response)

var routeData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(httpContext));

// Extract the data    
var values = routeData.Values;
var controllerName = values["controller"];
var actionName = values["action"];
var areaName = values["area"];
Run Code Online (Sandbox Code Playgroud)

  • 使用 `querystring = Request.UrlReferre.GetComponents(UriComponents.Query,UriFormat.UriEscaped);` 作为查询字符串。 (2认同)