Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UrlHelper.Action throws ArgumentNullException

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.

like image 420
Dan Avatar asked Jul 28 '15 15:07

Dan


1 Answers

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

like image 101
haim770 Avatar answered Oct 08 '22 02:10

haim770