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

问题描述 投票:0回答:3

我正在开发一个 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"
    }
  }
}

应用程序设置.json

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

请任何人帮我找出错误。

asp.net-core asp.net-core-webapi dotnet-httpclient httpclientfactory asp.net-core-6.0
3个回答
3
投票

好的尝试一下:

应用程序设置.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"
    }
  }
}

0
投票

您正在从应用程序设置中加载 -

Payments:TestOpayo:Url
builder.Configuration.GetValue<string>("Payments:TestOpayo:Url")

因此您应该在生产环境的应用程序设置中配置该参数。

有一个约定 .net 6 文档 用于将应用程序设置映射到环境(开发、生产)。

看起来您的生产应用程序设置中缺少

Payments:TestOpayo:Url

您还应该使用

__
作为分隔符以与平台无关,这导致了关键:
Payments__TestOpayo__Url


0
投票

这不是答案,我的应用程序中也有同样的问题。但我的 appsettings.json 文件中已经有了所有详细信息,不知道为什么仍然收到有关 System.ArgumentNullException: Value can not be null 的错误消息。 (参数'uriString')

© www.soinside.com 2019 - 2024. All rights reserved.