2

问题

我目前正在为 ASP.net MVC 3 构建一个助手,并且在考虑 UrlHelper.Action() 方法时遇到了问题。除了第一个请求(应用程序启动后)之外的每个请求,以下代码都会引发 NullReferenceException。

var src = htmlHelper.Url().Action("Css", "Asset", options);

相关堆栈

System.Web.HttpServerVarsCollection.Get(String name) +8740566
   System.Web.Mvc.UrlRewriterHelper.WasThisRequestRewritten(HttpContextBase httpContext) +42
   System.Web.Mvc.UrlRewriterHelper.WasRequestRewritten(HttpContextBase httpContext) +23
   System.Web.Mvc.PathHelpers.GenerateClientUrlInternal(HttpContextBase httpContext, String contentPath) +163
   System.Web.Mvc.PathHelpers.GenerateClientUrl(HttpContextBase httpContext, String contentPath) +63
   System.Web.Mvc.UrlHelper.GenerateUrl(String routeName, String actionName, String controllerName, RouteValueDictionary routeValues, RouteCollection routeCollection, RequestContext requestContext, Boolean includeImplicitMvcValues) +150
   System.Web.Mvc.UrlHelper.Action(String actionName, String controllerName, Object routeValues) +55

可能的原因

我使用了一个名为 AttributeRouting 的库,我通过 nuget 安装了它,并认为这可能会导致问题,但删除引用没有效果。

因为它确实可以在第一个请求中工作,但之后的每个请求都失败了,所以我觉得它与在应用程序启动时运行但应该在请求启动时运行的代码有关,或者某些变量/对象没有保留在请求中.

额外信息

htmlHelper.Url() 是下面的扩展方法。

public static UrlHelper Url(this HtmlHelper helper)
{
    return new UrlHelper(helper.ViewContext.RequestContext);
}
4

2 回答 2

0

你有没有解决过这个问题?我最近在安装 IIS 7 Url Rewrite Module v.2.0 时看到了这个错误。卸载后问题就消失了。

于 2011-11-16T02:08:51.877 回答
0

var src = htmlHelper.Url().Action("Css", "Asset", options);您是在视图中还是在您的一个控制器中使用它?

无论哪种方式,都应该定义自己的 Url 对象(我在这里假设您使用的 htmlHelper 对象是您自己创建的对象)。

public class MyController : Controller
{
    ....
    public ActionResult Index()
    {
        var src = Url.Action("Css", "Asset", options);
        ....
    }
}

或在您看来:

<head>
    <meta charset="UTF-8">
    <title>@ViewBag.Title</title>
    @{
        var src = Url.Action("Css", "Asset", options);
    }
    <link rel="Stylesheet" href="@src" />

或者更好,只是<link rel="Stylesheet" href="@Url.Action("Css","Asset",options)" />

于 2011-08-28T21:10:09.013 回答