如何知道哪个控制器/操作用户被重定向?

时间:2022-04-29 17:12:50

Being inside controller action or view, is there any way to know which controller/action user has been just redirected from? There is Request.UrlReferrer, but it's Url, I need to know Controller and/or action names instead.

作为控制器内部操作或视图,有什么方法可以知道哪个控制器/操作用户刚被重定向?有Request.UrlReferrer,但它是Url,我需要知道Controller和/或动作名称。

1 个解决方案

#1


0  

There is Request.UrlReferrer, but it's Url, I need to know Controller and/or action names instead.

有Request.UrlReferrer,但它是Url,我需要知道Controller和/或动作名称。

Given an Url as string you could parse it and obtain the corresponding controller and action names using the following approach:

给定一个Url作为字符串,您可以使用以下方法解析它并获取相应的控制器和操作名称:

var url = new Uri("http://example.com/somecontroller/someaction?foo=bar");

var request = new HttpRequest(null, url.AbsoluteUri, url.Query);
var response = new HttpResponse(StringWriter.Null);
var httpContext = new HttpContext(request, response);

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

string controllerName = (string)routeData.Values["controller"];
string actionName = (string)routeData.Values["action"];

Obviously at the place where I used http://example.com/somecontroller/someaction?foo=bar you could use Request.UrlReferrer.AbsoluteUri.

显然,在我使用http://example.com/somecontroller/someaction?foo=bar的地方你可以使用Request.UrlReferrer.AbsoluteUri。

Needless to say that this approach is absolutely unreliable. A much better solution is to simply pass the required information as parameters to the controller action from the calling action.

不用说,这种方法绝对不可靠。更好的解决方案是简单地将所需信息作为参数传递给调用操作中的控制器操作。

#1


0  

There is Request.UrlReferrer, but it's Url, I need to know Controller and/or action names instead.

有Request.UrlReferrer,但它是Url,我需要知道Controller和/或动作名称。

Given an Url as string you could parse it and obtain the corresponding controller and action names using the following approach:

给定一个Url作为字符串,您可以使用以下方法解析它并获取相应的控制器和操作名称:

var url = new Uri("http://example.com/somecontroller/someaction?foo=bar");

var request = new HttpRequest(null, url.AbsoluteUri, url.Query);
var response = new HttpResponse(StringWriter.Null);
var httpContext = new HttpContext(request, response);

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

string controllerName = (string)routeData.Values["controller"];
string actionName = (string)routeData.Values["action"];

Obviously at the place where I used http://example.com/somecontroller/someaction?foo=bar you could use Request.UrlReferrer.AbsoluteUri.

显然,在我使用http://example.com/somecontroller/someaction?foo=bar的地方你可以使用Request.UrlReferrer.AbsoluteUri。

Needless to say that this approach is absolutely unreliable. A much better solution is to simply pass the required information as parameters to the controller action from the calling action.

不用说,这种方法绝对不可靠。更好的解决方案是简单地将所需信息作为参数传递给调用操作中的控制器操作。