本文介绍了我如何在构建ASP.NET MVC没有ViewContext路线?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个实用工具类的路由不具有访问ViewContext。

I want to create a route from a utility class that doesn't have access to a ViewContext.

这可能吗?目前似乎没有为 ViewContext.Current

Is this possible? There doesnt seem to be any equivalent of ViewContext.Current

我在所有构造函数用于路由试图围绕捕鱼和HttpContext的,但不能完全得到我想要的东西。

I've tried fishing around in all the constructors for Routing and HttpContext but can't quite get to what I want.

这就是我要找的 - 尽管这并不工作,因为 RouteTable.Routes 的类型为 RouteCollection 而不是的RouteData 。如此接近 - 又那么远: - )

This is what I'm looking for - although this doesn't work because RouteTable.Routes is of type RouteCollection and not RouteData. So close - yet so far :-)

        RequestContext requestContext = new RequestContext(HttpContext.Current, RouteTable.Routes);
        UrlHelper url = new UrlHelper(requestContext);
        var urlString = url.RouteUrl(new {controller="DynamicImage", action="Button", text="Hello World"});

请注意:RequestContest的类型是System.Web.Routing.RequestContext,而不是HttpContext的

Note: RequestContest is of type System.Web.Routing.RequestContext and not HttpContext

推荐答案

试试这个:

var httpContext = new HttpContextWrapper(HttpContext.Current);
var requestContext = new RequestContext(httpContext);
var urlHelper = new UrlHelper(requestContext, new RouteData()));

希望这有助于

更新:

在previous是不正确的(我已经从我的记忆中贴吧)。试试这个(它在我的项目之一):

The previous is not correct (I've posted it from my memory). Try this instead (it works in one of my projects):

var httpContext = new HttpContextWrapper(HttpContext.Current);
var requestContext = new RequestContext(httpContext, new RouteData());
var urlHelper = new UrlHelper(requestContext);

新的RouteData()使用仅仅只为 RequestContext的初始化和新UrlHelper( RequestContext的)实际上调用新UrlHelper(RequestContext的,RouteTable.Routes)

new RouteData() is using just only for RequestContext initialization and new UrlHelper(requestContext) actually calls new UrlHelper(requestContext, RouteTable.Routes)

这篇关于我如何在构建ASP.NET MVC没有ViewContext路线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 21:50