【问题标题】:IUrlHelper Url.Action() throwing null parameter exceptionIUrlHelper Url.Action() 抛出空参数异常
【发布时间】:2021-09-13 08:10:30
【问题描述】:

我正在.NET Core MVC (.NET 5.0) 框架中开发一个 Web 应用程序。 我有一个继承自ControllerBase (Microsoft.AspNetCore.Mvc) 的类,我在其中开发了一个方法,它将actionNamecontrollerNameport 作为参数并将URL 作为Uri 对象返回。

在方法中,我使用 UriBuilder 并通过 IUrlHelpler 的 Url.Action(action, controller) 分配 Path,这给了我以下错误: p>

异常消息:

值不能为空。 (参数“助手”)

堆栈跟踪:

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

我的代码:

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;
            }
        }

根据堆栈跟踪日志,似乎我需要将 IUrlHelper 的对象作为参数传递给 Url.Action 方法。但实际上该方法并没有采用任何这样的参数。

我访问了以下链接,但没有得到太多帮助:

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

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

【问题讨论】:

    标签: c# asp.net-core-mvc


    【解决方案1】:

    尝试使用上下文:

    UrlHelper(HttpContext.Current.Request.RequestContext).Action(actionName, controllerName)
    

    【讨论】:

      【解决方案2】:
      1. 请检查你在这个控制器中是否有“return view()”,否则参数将不会返回。
      2. 尝试使用接口“IUrlHelper.Action()”创建一个实例来生成路径。 a link

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-05-22
        • 2017-09-02
        • 2012-09-09
        • 2015-09-25
        • 2023-04-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多