部署到IIS ASP.NET CORE6时ConnectionString为secrets.json的问题

bkkx9g8r  于 2023-08-05  发布在  .NET
关注(0)|答案(2)|浏览(99)

编辑:问题在于secrets.json连接字符串。由于它位于secrets.json中,而secrets.json不是应用程序文件夹的一部分,因此运行应用程序的任何IIS组件都无法访问它。现在我需要一个建议,如果有一种方法可以使secrets.json中的整个ConnectionString在生产环境中工作。这不是我所知道的最好的实践解决方案,但对于目前的使用来说是可以接受的。
编辑结束
我已经根据许多在线指南将我的ASP.NET CORE 6应用程序部署到了一个文件夹中。经过几次尝试和错误,我已经使它工作。为了进一步说明,我将讨论如何运行应用程序,如下所示:启动这个exe。
x1c 0d1x的数据
然后我把localhsot:5000放进我的浏览器,应用程序就运行了。
但是!它曾经有这样的错误:
处理您的请求时出错。
在检查EventLog后,我发现我的应用在部署时找不到ConnectionString。很公平,我的代码隐藏在secret.json中。我不得不把这行代码放到program.cs中

if (!(builder.Environment.IsDevelopment()))
{
    builder.Configuration.AddUserSecrets<Program>();
}

字符串
然后它开始工作,错误就没有了。
我需要的是让应用程序从IIS环境运行,如下所示:
1.我启动IIS应用程序。
1.在左侧面板中找到我的网站。
1.点击右侧面板中的“浏览网页”链接。
这将在我的浏览器中加载应用程序。但你瞧!无法访问的ConnectionString错误又回来了!
这里有一些笔记。我把所有的东西都部署好了。物理路径在我的网站是针对文件已经工作和前面提到的exe。事件日志错误将在此问题的末尾提供。
我的整个program.cs代码如下:

using Microsoft.AspNetCore.Authentication.Negotiate;
using Microsoft.EntityFrameworkCore;
using AktualniSchemaHfEditor.Data;
using System.Configuration;
using AktualniSchemaHfEditor.Models;
using System;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.Authorization;
using System.Net;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();

builder.Services.AddAuthentication(NegotiateDefaults.AuthenticationScheme)
   .AddNegotiate();

builder.Services.AddAuthorization(options =>
{
    // By default, all incoming requests will be authorized according to the default policy.
    options.FallbackPolicy = options.DefaultPolicy;
});
builder.Services.AddRazorPages();

if (builder.Environment.IsProduction())
{
    builder.Configuration.AddUserSecrets<Program>();
}

builder.Services.AddDbContext<AktualniSchemaHfEditor.Data.ModelContext>(options =>
        options.UseOracle(builder.Configuration.GetConnectionString("Default")));

var users = File.ReadAllLines("D:\\Users\\992960t\\source\\repos\\AktualniSchemaHfEditor\\AllowedUsers\\AllowedUsersList.txt");

builder.Services.AddMvc(config =>
{
    var policy = new AuthorizationPolicyBuilder()
                   .RequireAssertion(x =>
                         users.Any(
                             u => u.Equals(
                                 x.User.Identity!.Name, StringComparison.OrdinalIgnoreCase
                             )
                         )
                    )
                   .Build();
    config.Filters.Add(new AuthorizeFilter(policy));
});

//Následující kód je alternativa k ověřování uživatelů výše. Akorát jde o konkrétní výčet nikoliv čtení ze složky.

//builder.Services.AddMvc(config =>
//{
//    var policy = new AuthorizationPolicyBuilder()
//                   .RequireAssertion(x =>
//                         x.User.Identity!.Name == "VSSKB\\992960t" ||
//                         x.User.Identity!.Name == "VSSKB\\990967y"
//                         )
//                   .Build();
//    config.Filters.Add(new AuthorizeFilter(policy));
//});

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{RowId?}");

app.Run();


请帮助我,并有一个伟大的一天。
事件日志错误:

类别:Microsoft. AspNetCore. Diagnostics. ExceptionHandlerMiddleware EventId:1 SpanId:474bc069eae9db4e TraceId:436cb73eb448c3c5ab5b85befc99d45b ParentId:请求ID:8000000f-0002-fd00-b63f-84710c7967bb请求路径:/AktualniSchemaHf/Index执行请求时发生未处理的异常。异常:System. ArgumentNullException:值不能为空。(参数“connectionString”)。EntityFrameworkCore.公用事业。检查。Microsoft的NotEmpty(String value,String parameterName)。EntityFrameworkCore. OracleDbContextOptionsExtensions。在Microsoft中使用Oracle(DbContextOptionsBuilder optionsBuilder,String connectionString,Action 1 oracleOptionsAction) at Program.<>c__DisplayClass0_0.<<Main>$>b__1(DbContextOptionsBuilder options) in D:\Users\992960t\source\repos\AktualniSchemaHfEditor\Program.cs:line 28 at Microsoft.Extensions.DependencyInjection.EntityFrameworkServiceCollectionExtensions.<>c__DisplayClass1_0 2.b__0(IServiceProvider_,DbContextOptionsBuilder b)。扩展。DependencyInjection. EntityFrameworkServiceCollectionExtensions。Microsoft的CreateDbContextOptions [TContext](IServiceProvider applicationServiceProvider,Action 2 optionsAction) at Microsoft.Extensions.DependencyInjection.EntityFrameworkServiceCollectionExtensions.<>c__DisplayClass17_0 1.b__0(IServiceProvider p)。扩展。DependencyInjection.服务查找。CallSiteRuntimeResolver。Microsoft的VisitFactory(FactoryCallSite factoryCallSite,RuntimeResolverContext context)。扩展。DependencyInjection.服务查找。Microsoft的CallSiteVisitor 2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache(ServiceCallSite callSite, RuntimeResolverContext context) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor 2.VisitCallSite(ServiceCallSite callSite,TArgument argument)。扩展。DependencyInjection.服务查找。CallSiteRuntimeResolver。Microsoft中的VisitConstructor(ConstructorCallSite constructorCallSite,RuntimeResolverContext context)。扩展。DependencyInjection.服务查找。Microsoft的CallSiteVisitor 2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache(ServiceCallSite callSite, RuntimeResolverContext context) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor 2.VisitCallSite(ServiceCallSite callSite,TArgument argument)。扩展。DependencyInjection.服务查找。CallSiteRuntimeResolver。在Microsoft.Extensions.DependencyInjection.ServiceLookup.DynamicServiceProviderEngine中解析(ServiceCallSite callSite,ServiceProviderEngineScope范围)。<> c__DisplayClass2_0.b__0(ServiceProviderEngineScope范围),位于Microsoft。扩展。DependencyInjection.服务提供商。Microsoft中的GetService(Type serviceType,ServiceProviderEngineScope serviceProviderEngineScope)。扩展。DependencyInjection.服务查找。ServiceProviderEngineScope。Microsoft的GetService(Type serviceType)。扩展。DependencyInjection. ActivatorUtilities。Microsoft.AspNetCore.Mvc.Controllers.ControllerActivatorProvider中lambda_method19(Closure,IServiceProvider,Object [])处的GetService(IServiceProvider sp,Type type,Type requiredBy,Boolean isDefaultParameterRequired)。<> c__DisplayClass7_0.b__0(ControllerContext controllerContext),位于Microsoft.AspNetCore.Mvc.Controller.ControllerFactoryProvider。<> c__DisplayClass6_0.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()-从上一位置开始的堆栈跟踪结束-at Microsoft. AspNetCore. Mvc. Infrastructure. ResourceInvoker. g__等待|25_0(ResourceInvoker invoker,Task lastTask,State next,Scope scope,Object state,Boolean isCompleted)at Microsoft. AspNetCore. Mvc. Infrastructure. ResourceInvoker. Rethrow(ResourceExecutedContextSealed context)at Microsoft. AspNetCore. Mvc. Infrastructure. ResourceInvoker. Next(State & next,Scope & scope,Object & state,Boolean & isCompleted)at Microsoft. AspNetCore. Mvc. Infrastructure. ResourceInvoker. InvokeFilterPipelineAsync()-从上一位置开始的堆栈跟踪结束-at Microsoft. AspNetCore. Mvc. Infrastructure. ResourceInvoker. g__Awaited| 17_0(ResourceInvoker invoker,Task task,IDisposable scope)at Microsoft. AspNetCore. Mvc. Infrastructure. ResourceInvoker. g__Awaited| 17_0(ResourceInvoker调用程序,Task任务,IDisposable范围),位于Microsoft. AspNetCore. Routing. EndpointMiddleware. g__AwaitRequestTask| 6_0(Endpoint endpoint,Task requestTask,ILogger logger)at Microsoft. AspNetCore. Authorization. Policy. AuthorizationMiddlewareResultHandler. HandleAsync(RequestDelegate next,HttpContext context,AuthorizationPolicy policy,PolicyAuthorizationResult authorizeResult)at Microsoft. AspNetCore. AuthorizationMiddleware. Invoke(HttpContext context)at Microsoft. AspNetCore. Authentication. AuthenticationMiddleware. Invoke(HttpContext context)at Microsoft. AspNetCore. Diagnostics. ExceptionHandlerMiddleware. g__Awaited| 6_0(ExceptionHandlerMiddleware中间件,HttpContext上下文,Task任务)

unhi4e5o

unhi4e5o1#

根据您的描述,我认为您在部署应用程序时没有提供连接字符串。
我建议你可以添加ConnectionStrings appsettings.json文件,如下所示:

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

字符串

3zwjbxry

3zwjbxry2#

当应用部署在IIS上时,secret.json不能用于生产中的ConnectionString存储,因为它不是应用根文件夹的一部分。这样做会破坏秘密的目的。因此,在生产中使用不同的方法来存储ConnectionString。例如环境变量。必须在服务器上设置这些。在IIS管理器中,右键单击站点,转到配置管理器,将路径更改为system.webServer/aspNetCore,并找到带有EV的行。在这里设置saif变量的名称和内容。其他选项是Azure KeyValut,但我还没有使用它。

相关问题