Access System.Web.Routing.RequestContext from a static context in MVC 2.0

I need to use System.Web.Routing.RequestContext in the view model to call HtmlHelper.GenerateLink() .

In MVC 1.0, it was possible to get the context statically by pressing the current IHttpHandler :

  var context = ((MvcHandler) HttpContext.Current.CurrentHandler).RequestContext; 

Now the project has been upgraded to MVC 2.0, and this exception has been selected as part of:

Cannot pass an object of type "ServerExecuteHttpHandlerWrapper" to enter "System.Web.Mvc.MvcHandler".

I'm not sure if this is relevant, but it runs in .NET 4.0 on IIS6.

+6
source share
2 answers

I do not know what you want to do with System.Web.Routing.RequestContext ? Departure:

 var context = new HttpContextWrapper(System.Web.HttpContext.Current); var routeData = RouteTable.Routes.GetRouteData(context); // Use RouteData directly: var controller = routeData.Values["controller"]; // Or with via your RequestContext: var requestContext = new RequestContext(context, routeData); controller = requestContext.RouteData.Values["controller"] 
+11
source

I need to use System.Web.Routing.RequestContext in a view model to call HtmlHelper.GenerateLink ().

Although theoretically you can write:

 var rc = HttpContext.Current.Request.RequestContext; 

in practice, you absolutely should not do something like this in the presentation model. What HTML helpers should do:

 public static MvcHtmlString GenerateMyLink<MyViewModel>(this HtmlHelper<MyViewModel> html) { MyViewModel model = html.ViewData.Model; RequestContext rc = html.ViewContext.RequestContext; //TODO: use your view model and the HttpContext to generate whatever link is needed ... } 

and in your strongly typed view, MyViewModel is simple:

 <%= Html.GenerateMyLink() %> 
+16
source

Source: https://habr.com/ru/post/889092/


All Articles