Asp.net MVC3 UrlHelper.Action()抛出NullReferenceException

时间:2011-08-24 07:57:39

标签: asp.net-mvc-3 c#-4.0 razor asp.net-routing

问题

我正在为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的lib,我通过nuget安装,并认为这可能会导致问题,但删除引用无效。

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

额外信息

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

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

2 个答案:

答案 0 :(得分: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)" />

答案 1 :(得分:0)

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

相关问题