How do I get the Controller and Action names from the Referrer Uri?

前端 未结 9 1051
清歌不尽
清歌不尽 2020-12-01 14:06

There\'s a lot of information for building Uris from Controller and Action names, but how can I do this the other way around?

Basically, all I\'m trying to achieve i

9条回答
  •  长情又很酷
    2020-12-01 14:32

    Here is a lightweight way to do this without creating response objects.

    var values = RouteDataContext.RouteValuesFromUri(Request.UrlReferrer);
    
    var controllerName = values["controller"];
    var actionName = values["action"];
    

    Uses this custom HttpContextBase class

    public class RouteDataContext : HttpContextBase {
        public override HttpRequestBase Request { get; }
    
        private RouteDataContext(Uri uri) {
            var url = uri.GetLeftPart(UriPartial.Path);
            var qs = uri.GetComponents(UriComponents.Query,UriFormat.UriEscaped);
    
            Request = new HttpRequestWrapper(new HttpRequest(null,url,qs));
        }
    
        public static RouteValueDictionary RouteValuesFromUri(Uri uri) {
            return RouteTable.Routes.GetRouteData(new RouteDataContext(uri)).Values;
        }
    }
    

提交回复
热议问题