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