【发布时间】:2011-08-24 07:57:38
【问题描述】:
问题
我目前正在为 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);
}
【问题讨论】:
-
升级到 MVC3 后我遇到了同样的问题 - 当所有单元测试一起运行时,所有调用 UrlHelper 的测试都会失败。如果我单独运行它们,甚至通过控制器运行它们,它们就会通过。你找到解决办法了吗?
标签: asp.net-mvc-3 c#-4.0 razor asp.net-routing