处理请求时发生未处理的异常。 - 配置 program.cs?
An unhandled exception occurred while processing the request. - configuration program.cs?
我在从数据库中检索数据时遇到通信问题
合同数据服务
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ContractShortening.Core.Entities;
using ContractShortening.Core.Interfaces;
using ContractShortening.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;
namespace ContractShortening.Infrastructure.Services;
public class ContractDataService : IContractDataService
{
private readonly DataDbContext _context;
//Task<IQueryable<ContractData>> ExecAsync(string ContractNumberPar);
public async Task<IQueryable<ContractData>> ExecAsync(string contractNumberPar)
{
return _context.ContractData
.FromSqlRaw("[egeria].[ContractData_P] " + contractNumberPar);
}
}
DataDbContext
using Ardalis.EFCore.Extensions;
using ContractShortening.Core;
using ContractShortening.SharedKernel;
using MediatR;
using Microsoft.EntityFrameworkCore;
using ContractShortening.Core.Entities;
namespace ContractShortening.Infrastructure.Data
{
public class DataDbContext : DbContext
{
public DataDbContext(DbContextOptions<DataDbContext> options)
: base(options)
{
}
public DbSet<ContractData> ContractData { get; }
}
}
IContractDataService
using System.Threading.Tasks;
using ContractShortening.Core.Entities;
namespace ContractShortening.Core.Interfaces
{
public interface IContractDataService
{
Task<IQueryable<ContractData>> ExecAsync(string ContractNumberPar);
}
}
DataApiController
using DevExtreme.AspNet.Data;
using DevExtreme.AspNet.Mvc;
using Microsoft.AspNetCore.Mvc;
using ContractShortening.Core.Interfaces;
namespace ContractShortening.Web.Api
{
[Route("api/[controller]/[action]")]
public class DataApiController : Controller
{
private readonly IContractDataService _data;
public DataApiController(
IContractDataService data
)
{
_data = data;
}
[HttpGet]
public async Task<IActionResult> GetQuery(DataSourceLoadOptions loadOptions, string contractNumberPar)
{
var processes = (await _data.ExecAsync("35/0698/19")).Select(i => new
{
i.ContractNumber
,i.TypeOfLeasing
,i.CodeClient
,i.Short
,i.NameOfClient
,i.Amortization
,i.Currency
,i.ContractValue
,i.NumberOfInstallments
,i.FinalValue
,i.FinalValuePercent
,i.TypeOfBaseRate
,i.ValueOfBaseRate
,i.REFI
,i.InstallmentNumber
,i.Type
,i.MaturityDate
,i.NetAmount
,i.CapitalRemaining
});
return Json(DataSourceLoader.Load(processes, loadOptions));
}
}
}
Program.cs
using Ardalis.ListStartupServices;
using Autofac;
using Autofac.Extensions.DependencyInjection;
using ContractShortening.Core;
using ContractShortening.Infrastructure;
using ContractShortening.Core.Interfaces;
using ContractShortening.Infrastructure.Data;
using ContractShortening.Infrastructure.Services;
using ContractShortening.Web;
using Microsoft.OpenApi.Models;
using Microsoft.Extensions.Configuration;
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
builder.Services.Configure<CookiePolicyOptions>(options =>
{
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
builder.Services.AddScoped<IActiveDirectoryService, ActiveDirectoryService>();
string defaultConnection = builder.Configuration.GetConnectionString("DefaultConnection");
string seriLogDB = builder.Configuration.GetConnectionString("SeriLogDB");
string ADConnection = builder.Configuration.GetConnectionString("ADConnection");
builder.Services.AddDbContext(defaultConnection);
//builder.Services.AddDbContext(seriLogDB);
//builder.Services.AddDbContext(ADConnection);
builder.Services.AddDbContext<ActiveDirectoryDbContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString(ADConnection)));
builder.Services.AddDbContext<DataDbContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString(defaultConnection)));
//builder.Services.AddDbContext<AppDbContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString(defaultConnection)));
builder.Services.AddControllersWithViews().AddNewtonsoftJson();
builder.Services.AddRazorPages();
#region snippet_MigrationsAssembly
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(
builder.Configuration.GetConnectionString(defaultConnection),
x => x.MigrationsAssembly("ContractShortening.Migration")));
#endregion
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
c.EnableAnnotations();
});
// add list services for diagnostic purposes - see https://github.com/ardalis/AspNetCoreStartupServices
builder.Services.Configure<ServiceConfig>(config =>
{
config.Services = new List<ServiceDescriptor>(builder.Services);
// optional - default path to view services is /listallservices - recommended to choose your own path
config.Path = "/listservices";
});
//builder.Host.ConfigureContainer<ContainerBuilder>(containerBuilder =>
//{
// //containerBuilder.RegisterModule(new DefaultCoreModule());
// //containerBuilder.RegisterModule(new DefaultInfrastructureModule(builder.Environment.EnvironmentName == "Development"));
//});
builder.Logging.ClearProviders();
builder.Logging.AddConsole();
//builder.Logging.AddAzureWebAppDiagnostics(); add this if deploying to Azure
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseShowAllServicesMiddleware();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseRouting();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
// Enable middleware to serve generated Swagger as a JSON endpoint.
app.UseSwagger();
// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), specifying the Swagger JSON endpoint.
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"));
app.UseEndpoints(endpoints =>
{
endpoints.MapDefaultControllerRoute();
endpoints.MapRazorPages();
});
// Seed Database
using (var scope = app.Services.CreateScope())
{
var services = scope.ServiceProvider;
try
{
var context = services.GetRequiredService<AppDbContext>();
//context.Database.Migrate();
context.Database.EnsureCreated();
SeedData.Initialize(services);
}
catch (Exception ex)
{
var logger = services.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "An error occurred seeding the DB.");
}
}
app.Run();
错误
An unhandled exception occurred while processing the request.
InvalidOperationException: Unable to resolve service for type
'ContractShortening.Core.Interfaces.IContractDataService' while attempting to activate
'ContractShortening.Web.Api.DataApiController'.
Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider
sp, Type type, Type requiredBy, bool isDefaultParameterRequired)
Stack Query Cookies Headers Routing
InvalidOperationException: Unable to resolve service for type > 'ContractShortening.Core.Interfaces.IContractDataService' while attempting to activate > 'ContractShortening.Web.Api.DataApiController'.
Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider > sp, Type type, Type requiredBy, bool isDefaultParameterRequired)
lambda_method620(Closure , IServiceProvider , object[] )
Microsoft.AspNetCore.Mvc.Controllers.ControllerActivatorProvider+<>c__DisplayClass7_0. > b__0(ControllerContext controllerContext)
Microsoft.AspNetCore.Mvc.Controllers.ControllerFactoryProvider+<>c__DisplayClass6_0. > g__CreateController|0(ControllerContext controllerContext)
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(ref State next, ref > Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker. > g__Awaited|25_0(ResourceInvoker invoker, Task lastTask, State > next, Scope scope, object state, bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSeale > d context)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(ref State next, ref Scope > scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker. > g__Logged|17_1(ResourceInvoker invoker)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker. > g__Logged|17_1(ResourceInvoker invoker)
Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(Endpoint > endpoint, Task requestTask, ILogger logger)
Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, > ISwaggerProvider swaggerProvider)
Ardalis.ListStartupServices.ShowAllServicesMiddleware.Invoke(HttpContext httpContext)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext > context)
显示原始异常详细信息
添加
builder.Services.AddScoped<IContractDataService, ContractDataService>()
// Or depending on your service behavior [..].AddTransient(..) or [..].AddSingleton(..)
...给你的Program.cs
我在从数据库中检索数据时遇到通信问题
合同数据服务
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ContractShortening.Core.Entities;
using ContractShortening.Core.Interfaces;
using ContractShortening.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;
namespace ContractShortening.Infrastructure.Services;
public class ContractDataService : IContractDataService
{
private readonly DataDbContext _context;
//Task<IQueryable<ContractData>> ExecAsync(string ContractNumberPar);
public async Task<IQueryable<ContractData>> ExecAsync(string contractNumberPar)
{
return _context.ContractData
.FromSqlRaw("[egeria].[ContractData_P] " + contractNumberPar);
}
}
DataDbContext
using Ardalis.EFCore.Extensions;
using ContractShortening.Core;
using ContractShortening.SharedKernel;
using MediatR;
using Microsoft.EntityFrameworkCore;
using ContractShortening.Core.Entities;
namespace ContractShortening.Infrastructure.Data
{
public class DataDbContext : DbContext
{
public DataDbContext(DbContextOptions<DataDbContext> options)
: base(options)
{
}
public DbSet<ContractData> ContractData { get; }
}
}
IContractDataService
using System.Threading.Tasks;
using ContractShortening.Core.Entities;
namespace ContractShortening.Core.Interfaces
{
public interface IContractDataService
{
Task<IQueryable<ContractData>> ExecAsync(string ContractNumberPar);
}
}
DataApiController
using DevExtreme.AspNet.Data;
using DevExtreme.AspNet.Mvc;
using Microsoft.AspNetCore.Mvc;
using ContractShortening.Core.Interfaces;
namespace ContractShortening.Web.Api
{
[Route("api/[controller]/[action]")]
public class DataApiController : Controller
{
private readonly IContractDataService _data;
public DataApiController(
IContractDataService data
)
{
_data = data;
}
[HttpGet]
public async Task<IActionResult> GetQuery(DataSourceLoadOptions loadOptions, string contractNumberPar)
{
var processes = (await _data.ExecAsync("35/0698/19")).Select(i => new
{
i.ContractNumber
,i.TypeOfLeasing
,i.CodeClient
,i.Short
,i.NameOfClient
,i.Amortization
,i.Currency
,i.ContractValue
,i.NumberOfInstallments
,i.FinalValue
,i.FinalValuePercent
,i.TypeOfBaseRate
,i.ValueOfBaseRate
,i.REFI
,i.InstallmentNumber
,i.Type
,i.MaturityDate
,i.NetAmount
,i.CapitalRemaining
});
return Json(DataSourceLoader.Load(processes, loadOptions));
}
}
}
Program.cs
using Ardalis.ListStartupServices;
using Autofac;
using Autofac.Extensions.DependencyInjection;
using ContractShortening.Core;
using ContractShortening.Infrastructure;
using ContractShortening.Core.Interfaces;
using ContractShortening.Infrastructure.Data;
using ContractShortening.Infrastructure.Services;
using ContractShortening.Web;
using Microsoft.OpenApi.Models;
using Microsoft.Extensions.Configuration;
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
builder.Services.Configure<CookiePolicyOptions>(options =>
{
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
builder.Services.AddScoped<IActiveDirectoryService, ActiveDirectoryService>();
string defaultConnection = builder.Configuration.GetConnectionString("DefaultConnection");
string seriLogDB = builder.Configuration.GetConnectionString("SeriLogDB");
string ADConnection = builder.Configuration.GetConnectionString("ADConnection");
builder.Services.AddDbContext(defaultConnection);
//builder.Services.AddDbContext(seriLogDB);
//builder.Services.AddDbContext(ADConnection);
builder.Services.AddDbContext<ActiveDirectoryDbContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString(ADConnection)));
builder.Services.AddDbContext<DataDbContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString(defaultConnection)));
//builder.Services.AddDbContext<AppDbContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString(defaultConnection)));
builder.Services.AddControllersWithViews().AddNewtonsoftJson();
builder.Services.AddRazorPages();
#region snippet_MigrationsAssembly
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(
builder.Configuration.GetConnectionString(defaultConnection),
x => x.MigrationsAssembly("ContractShortening.Migration")));
#endregion
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
c.EnableAnnotations();
});
// add list services for diagnostic purposes - see https://github.com/ardalis/AspNetCoreStartupServices
builder.Services.Configure<ServiceConfig>(config =>
{
config.Services = new List<ServiceDescriptor>(builder.Services);
// optional - default path to view services is /listallservices - recommended to choose your own path
config.Path = "/listservices";
});
//builder.Host.ConfigureContainer<ContainerBuilder>(containerBuilder =>
//{
// //containerBuilder.RegisterModule(new DefaultCoreModule());
// //containerBuilder.RegisterModule(new DefaultInfrastructureModule(builder.Environment.EnvironmentName == "Development"));
//});
builder.Logging.ClearProviders();
builder.Logging.AddConsole();
//builder.Logging.AddAzureWebAppDiagnostics(); add this if deploying to Azure
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseShowAllServicesMiddleware();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseRouting();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
// Enable middleware to serve generated Swagger as a JSON endpoint.
app.UseSwagger();
// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), specifying the Swagger JSON endpoint.
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"));
app.UseEndpoints(endpoints =>
{
endpoints.MapDefaultControllerRoute();
endpoints.MapRazorPages();
});
// Seed Database
using (var scope = app.Services.CreateScope())
{
var services = scope.ServiceProvider;
try
{
var context = services.GetRequiredService<AppDbContext>();
//context.Database.Migrate();
context.Database.EnsureCreated();
SeedData.Initialize(services);
}
catch (Exception ex)
{
var logger = services.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "An error occurred seeding the DB.");
}
}
app.Run();
错误
An unhandled exception occurred while processing the request. InvalidOperationException: Unable to resolve service for type
'ContractShortening.Core.Interfaces.IContractDataService' while attempting to activate
'ContractShortening.Web.Api.DataApiController'. Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider
sp, Type type, Type requiredBy, bool isDefaultParameterRequired)
Stack Query Cookies Headers Routing InvalidOperationException: Unable to resolve service for type > 'ContractShortening.Core.Interfaces.IContractDataService' while attempting to activate > 'ContractShortening.Web.Api.DataApiController'. Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider > sp, Type type, Type requiredBy, bool isDefaultParameterRequired) lambda_method620(Closure , IServiceProvider , object[] ) Microsoft.AspNetCore.Mvc.Controllers.ControllerActivatorProvider+<>c__DisplayClass7_0. > b__0(ControllerContext controllerContext) Microsoft.AspNetCore.Mvc.Controllers.ControllerFactoryProvider+<>c__DisplayClass6_0. > g__CreateController|0(ControllerContext controllerContext) Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(ref State next, ref > Scope scope, ref object state, ref bool isCompleted) Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync() Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker. > g__Awaited|25_0(ResourceInvoker invoker, Task lastTask, State > next, Scope scope, object state, bool isCompleted) Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSeale > d context) Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(ref State next, ref Scope > scope, ref object state, ref bool isCompleted) Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync() Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker. > g__Logged|17_1(ResourceInvoker invoker) Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker. > g__Logged|17_1(ResourceInvoker invoker) Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(Endpoint > endpoint, Task requestTask, ILogger logger) Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext) Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, > ISwaggerProvider swaggerProvider) Ardalis.ListStartupServices.ShowAllServicesMiddleware.Invoke(HttpContext httpContext) Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext > context)
显示原始异常详细信息
添加
builder.Services.AddScoped<IContractDataService, ContractDataService>()
// Or depending on your service behavior [..].AddTransient(..) or [..].AddSingleton(..)
...给你的Program.cs