5
votes

I am using the UrlHelper to generate an URL, however, I am getting the ArgumentNullException when I call the method Action(action, controller, route).

UrlHelper urlHelper = new UrlHelper();

if (!string.IsNullOrEmpty(notificacao.NotAction))
{ 
     NotRequestUrl = urlHelper.Action("myAction", "myController", HMTLHelperExtensions.convertStringToRouteValueDictionary(myparameters));
} 

I've created a helper function that creat to me the object route values (and it's working properly).

    public static RouteValueDictionary convertStringToRouteValueDictionary(string parametros)
    {
        RouteValueDictionary dicionario = new RouteValueDictionary();
        foreach (string parametro in parametros.Split(';'))
            if (parametro.Split('=').Count() == 2)
                dicionario.Add(parametro.Split('=')[0], parametro.Split('=')[1]);
        return dicionario;
    }

The most strange is that it's already working inside a controller, however, it isn't working in separate a class (like a BusinessLayer/Facade).

None of the arguments are nulls.

It's been calling from a Task method.

I also tried to get the Context like:

UrlHelper urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);

But it HttpContext.Current is returning null to me.

1
What does HMTLHelperExtensions.convertStringToRouteValueDictionary(myparameters) return?Luke
Return a list with route values.Dan
Obviously, but what does it actually return when it is run in your example? And what is the value of variable myparameters?Luke
sorry @Coulton. The value of myparameters are "id=2". The result returns a list of keys, in this case, a Key called id, with the value 2Dan

1 Answers

7
votes

You need to pass the current RequestContext. Otherwise, it has no way to generate the appropriate urls for you because it's lacking the context:

UrlHelper urlHelper = new UrlHelper(this.Request.RequestContext);

The default (parameter-less) constructor is intended for use by unit testing only (source).

See MSDN