Null reference exception when generating a url with UrlHelper.Action method

拈花ヽ惹草 提交于 2019-12-03 10:14:23

I had this problem, but it was unrelated to URL rewrite modules.

In my case, I accidentally cached an instance of UrlHelper in a static field, and later requests encountered a disposed instance from earlier requests.

I know this question is fairly old now, but I recently found myself in a very similar situation where my UrlHelper was giving me null reference exception on System.Web.HttpServerVarsCollection.Get as well.

The problem was indeed HTTP_X_ORIGINAL_URL and this particular server variable comes from the URL Rewrite 2.0 Module on IIS.

Interestingly enough this module was installed but not being used. However, just it's presence was enough to cause the problem. Uninstalling it made the error go away.

If you need to do URL re-writes there are other modules out there or you could do it at the application level.

Hope that helps.

I ran into this, in my case was able to solve by switching to a non-extension method usage of UrlHelper. I had one extension method calling another, but passing the UrlHelper to the 2nd method.

This way was broken:

public static string Script(this UrlHelper helper, string fileName)
{
    return Asset(helper, "~/js/", fileName);
}

private static string Asset(this UrlHelper helper, string path, string fileName)
{
    return helper.Content(string.Format("{0}/{1}/{2}",
           path,
           Version,
           fileName));
}

This way works:

public static string Script(this UrlHelper helper, string fileName)
{
    return Asset(helper, "~/js/", fileName);
}

private static string Asset(UrlHelper helper, string path, string fileName)
{
    return helper.Content(string.Format("{0}/{1}/{2}",
           path,
           Version,
           fileName));
}

Note the function signature difference of the Asset method.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!