So this is a line that does not work:
return (new UrlHelper(instance.htmlHelper.ViewContext.RequestContext)).Content(url);
We know that the instance is not null due to the line above, which already checks for null. Exceptional link exceptions are the most common unhandled exceptions and are also easiest to avoid. In general, you should never assume that properties or parameters that are null types are not null. I assume instance.htmlHelper is your problem. I assume htmlHelper is an instance of System.Web.Mvc.HtmlHelper. Therefore, ViewContext and RequestContext should not be null if it is a valid HtmlHelper created by MVC.
A simple solution is to check for zeros like:
if (instance.htmlHelper == null) { throw new InvalidOperationException("htmlHelper has not been populated."); } return (new UrlHelper(instance.htmlHelper.ViewContext.RequestContext)).Content(url);
Obviously, you could repeat this for ViewContext and RequestContext using MVC to populate them.
Now, assuming htmlHelper is null (the most likely situation), here you have a slight design problem. What you really have to do is extend the HtmlHelper class, not use a static method. Also, it looks like you are using some kind of static instance, which is probably also invalid in MVC. MVC typically creates controller instances and views for each request. You can still use the static method to implement web forms, but for MVC you have to extend the HtmlHelper like this:
public static MvcHtmlString GenerateUrl(this htmlHelper, string url) { return (new UrlHelper(htmlHelper.ViewContext.RequestContext)).Content(url); }
Make sure you always use the active HtmlHelper from MVC, and not some static instance. I'm not sure if ViewContext or RequestContext can be empty after the request is completed. I have never tried to save an HtmlHelper after a single request. Even if they are not null, otherwise they may be invalid and will cause problems below in the MVC pipeline.
Hope this helps.
source share