0

I am developing a web application in .NET Core MVC (.NET 5.0) framework. I have a class inherited from ControllerBase (Microsoft.AspNetCore.Mvc) in which I developed a method which will take actionName, controllerName, and port as parameters and return URL as Uri object.

In the method, I am using UriBuilder and assigning Path through IUrlHelpler's Url.Action(action, controller) which is giving me the following error:

Exception Message:

Value cannot be null. (Parameter 'helper')

Stack Trace:

at Microsoft.AspNetCore.Mvc.UrlHelperExtensions.Action(IUrlHelper helper, String action, String controller)

My Code:

public Uri UriUrlBuilder(string actionName, string controllerName, int? port)
        {
            try
            {
                _ = new AppSettingsConfiguration();
                UriBuilder uriBuilder = new()
                {
                    Host = AppSettings.BaseURL,
                    Scheme = "https",
                    Port = (int)port,
                    Path = Url.Action(actionName, controllerName)
                };
                return uriBuilder.Uri;
            }
            catch (Exception ex)
            {
                _ = new LogWriter("Class: Common. Method: UriUrlBuilder.  Error: " + ex.Message);
                return null;
            }
        }

According to Stack Trace logs, it seems like I need to pass IUrlHelper's object as a parameter in Url.Action method. But in actual that method is not taking any parameter like that.

I visited the following links but did not get much help:

How to use Url.Action() in a class file?

ASP.NET 5 - MVC 6 - Unit Test a Controller that uses Url.Action

2 Answers2

0

Try to use context:

UrlHelper(HttpContext.Current.Request.RequestContext).Action(actionName, controllerName)
Jackdaw
  • 7,626
  • 5
  • 15
  • 33
0
  1. Pls check whether u have "return view()" in this controller, otherwise the parameter will be not send back.
  2. Try to use the interface "IUrlHelper.Action()" to create a instance for generate the path. a link
Ran
  • 51
  • 2