应用程序引发了未处理的异常。 System.ArgumentNullException:值不能为空。 (参数'uriString')

Posted

技术标签:

【中文标题】应用程序引发了未处理的异常。 System.ArgumentNullException:值不能为空。 (参数\'uriString\')【英文标题】:An unhandled exception was thrown by the application. System.ArgumentNullException: Value cannot be null. (Parameter 'uriString')应用程序引发了未处理的异常。 System.ArgumentNullException:值不能为空。 (参数'uriString') 【发布时间】:2021-11-29 06:42:03 【问题描述】:

我正在做一个 asp .net core 6.0 web api 项目。

问题概述:

我遇到了一个问题。运行项目时,获取请求的响应为 200 ok。 但是在构建项目时,获取请求显示 500Internal Server Error 并且在终端中我也遇到了错误。

详情:

当我使用dotnet run 运行项目时(托管环境:开发,端口为7045 或5032), 而https://localhost:7045/api/public/opayo-payment/retrieve-transaction/9A5CAE22-7109-D006-A017-41BF9F138076这个get请求的响应是200

但是当我使用dotnet publish -c Release dotnet /home/PaymentApi.dll 构建项目时(托管环境:生产,端口为 5000 或 5001)

并且,https://localhost:5001/api/public/opayo-payment/retrieve-transaction/9A5CAE22-7109-D006-A017-41BF9F138076 这个获取请求的响应是500Internal Server Error

在终端我得到以下错误

fail: Microsoft.AspNetCore.Server.Kestrel[13]
      Connection id "0HMDJ000A9MDB", Request id "0HMDJ000A9MDB:00000002": An unhandled exception was thrown by the application.
      System.ArgumentNullException: Value cannot be null. (Parameter 'uriString')
         at System.Uri..ctor(String uriString)
         at Program.<>c__DisplayClass0_0.<<Main>$>b__1(HttpClient c) in /home/PaymentApi/Program.cs:line 16
         at Microsoft.Extensions.Http.DefaultHttpClientFactory.CreateClient(String name)
         at Microsoft.Extensions.DependencyInjection.HttpClientBuilderExtensions.AddTransientHelper[TClient,TImplementation](IServiceProvider s, IHttpClientBuilder builder)
         at Microsoft.Extensions.DependencyInjection.HttpClientBuilderExtensions.<>c__DisplayClass13_0`2.<AddTypedClientCore>b__0(IServiceProvider s)
         at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitFactory(FactoryCallSite factoryCallSite, RuntimeResolverContext context)
         at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
         at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitDisposeCache(ServiceCallSite transientCallSite, RuntimeResolverContext context)
         at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
         at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.Resolve(ServiceCallSite callSite, ServiceProviderEngineScope scope)
         at Microsoft.Extensions.DependencyInjection.ServiceLookup.DynamicServiceProviderEngine.<>c__DisplayClass2_0.<RealizeService>b__0(ServiceProviderEngineScope scope)
         at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
         at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType)
         at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired)
         at lambda_method9(Closure , IServiceProvider , Object[] )
         at Microsoft.AspNetCore.Mvc.Controllers.ControllerActivatorProvider.<>c__DisplayClass7_0.<CreateActivator>b__0(ControllerContext controllerContext)
         at Microsoft.AspNetCore.Mvc.Controllers.ControllerFactoryProvider.<>c__DisplayClass6_0.<CreateControllerFactory>g__CreateController|0(ControllerContext controllerContext)
         at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
         at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
      --- End of stack trace from previous location ---
         at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|20_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
         at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
         at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
         at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
         at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
         at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequests[TContext](IHttpApplication`1 application)

在程序.cs中

builder.Services.Configure<MerchantSessionConfig>(builder.Configuration.GetSection("Payments:TestOpayo"));
builder.Services.AddHttpClient<IOpayoPaymentService, OpayoPaymentService>("PublicOpayoApi", c =>
                c.BaseAddress = new Uri(builder.Configuration.GetValue<string>("Payments:TestOpayo:Url"))
                );

服务

private readonly HttpClient _client;
        private readonly IHttpClientFactory _clientFactory;
        private readonly MerchantSessionConfig _merchantSessionConfigoptions;

        private readonly DataDbContex _dataDbContex;

        public OpayoPaymentService(HttpClient client, IHttpClientFactory clientFactory, 
        IOptions<MerchantSessionConfig> options, DataDbContex dataDbContex)
                        
            client = clientFactory.CreateClient("PublicOpayoApi");
            _clientFactory = clientFactory;
            _client = client;
            _merchantSessionConfigoptions = options.Value;
            _dataDbContex = dataDbContex;

            // Basic Authentication
            _client.DefaultRequestHeaders.Add("Accept", "application/json");
            var authenticationString = $"_merchantSessionConfigoptions.Username:_merchantSessionConfigoptions.Password";
            var base64EncodedString = Convert.ToBase64String(System.Text.ASCIIEncoding.UTF8.GetBytes(authenticationString));
            _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", base64EncodedString);

        

appsettings.Development.json


  "Logging": 
    "LogLevel": 
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    
  ,
  "ConnectionStrings": 
    "DefaultConnection": "Server=<server>; port=5432; user id=postgres; password=<password>; database=<db>; Integrated Security=true; Pooling=true; CommandTimeout=300;Include Error Detail=true;Log Parameters=true"
  ,
  "Payments": 
    "TestOpayo": 
      "Url": "https://pi-test.sagepay.com",
      "VendorName": "vendor",
      "Username": "username",
      "Password": "password"
    
  

appsettings.json


  "Logging": 
    "LogLevel": 
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    
  ,
  "AllowedHosts": "*"


请任何人帮我找出错误。

【问题讨论】:

请添加您的应用设置和开发版本。 您好,我已添加 我已经给你发了答案 ;-)。将 Payments:TestOpayo:Url 添加到您的 prod appsettings ... 【参考方案1】:

好的,试试吧:

appsettings.json


  "Logging": 
    "LogLevel": 
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    
  ,
  "ConnectionStrings": 
    "DefaultConnection": "Server=<server>; port=5432; user id=postgres; password=<password>; database=<db>; Integrated Security=true; Pooling=true; CommandTimeout=300;Include Error Detail=true;Log Parameters=true"
  ,
  "Payments": 
    "TestOpayo": 
      "Url": "https://pi-test.sagepay.com",
      "VendorName": "vendor",
      "Username": "username",
      "Password": "password"
    
  

【讨论】:

【参考方案2】:

您正在从您的 appsettings 加载 - Payments:TestOpayo:Urlbuilder.Configuration.GetValue&lt;string&gt;("Payments:TestOpayo:Url")

所以你应该已经在生产环境的 appsettings 中配置了参数。

有一个约定 .net 6 documentation 用于将 appsettings 映射到环境(开发、生产)。

您的生产应用设置中似乎缺少Payments:TestOpayo:Url

您还应该使用__ 作为分隔符来与平台无关,这会导致关键:Payments__TestOpayo__Url

【讨论】:

以上是关于应用程序引发了未处理的异常。 System.ArgumentNullException:值不能为空。 (参数'uriString')的主要内容,如果未能解决你的问题,请参考以下文章

引发类型为“System.OutOfMemoryException”的异常。

为啥我的信号处理程序(引发异常)不会多次触发?

Django奇怪的SlugField验证,在clean()之前没有引发错误,返回了未清理的数据

AppDomain.AssemblyLoad 事件捕获事件处理程序中引发的所有异常

Eclipse - 在 Android 应用程序上引发未处理的异常时中断用户代码

PL/SQL 引发处理异常