0

我正在工作一个 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此获取请求的响应为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": "*"
}

请任何人帮我找出错误。

4

2 回答 2

1

好的试试看:

应用设置.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"
    }
  }
}
于 2021-11-29T07:44:00.297 回答
0

您正在加载 -Payments:TestOpayo:Urlbuilder.Configuration.GetValue<string>("Payments:TestOpayo:Url")您的 appsettings 中加载。

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

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

看起来您Payments:TestOpayo:Url在生产应用程序设置中丢失了。

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

于 2021-11-29T07:39:44.450 回答