当前位置: 首页 > 知识库问答 >
问题:

处理请求时发生未处理的异常。-配置program.cs?[重复]

康照
2023-03-14

从数据库中检索数据时出现通信问题

合同数据服务

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);
    }
}

DataApicController

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();



错误

处理请求时发生未经处理的异常。InvalidOperationException:无法解析ContractShorting类型的服务。果心接口。IContractDataService“试图激活ContractShorting时”。网状物应用程序编程接口。DataApicController’。微软扩展。依赖注入。ActivatorUtilities。GetService(IServiceProvider,Type Type,Type requiredBy,bool isDefaultParameterRequired)

堆栈查询Cookie标头路由InvalidOperationException:无法解析类型的服务

显示原始异常详细信息

共有1个答案

夏知
2023-03-14

添加

builder.Services.AddScoped<IContractDataService, ContractDataService>()
// Or depending on your service behavior [..].AddTransient(..) or [..].AddSingleton(..)

... 到您的程序。cs

关于DI的文档可以在这里找到

 类似资料:
  • 在我的代码中,所有请求都有一个超时期。对于每个请求,我都必须处理超时异常。有没有办法在请求中附加全局超时异常处理程序? 和上面一样,我每次都要处理超时和引发服务不可用。我想要一些通用的东西,每当超时发生,它将引起服务不可用。

  • 我有下一个spring批处理配置类: 启动应用程序时,我收到下一个异常:

  • 我主要是为技术精明的人编写一个小工具,例如程序员、工程师等,因为这些工具通常是快速的,随着时间的推移,我知道会有未处理的异常,用户不会介意。我希望用户能够向我发送回溯,这样我就可以检查发生了什么,并可能改进应用程序。 我通常做wxPython编程,但我最近做了一些Java。我已经将

  • 问题内容: 在处理JSF ajax请求时引发异常时,如何处理异常并访问堆栈跟踪?现在,当JSF项目阶段设置为Development时,我仅在JavaScript警报中获得异常类名称和消息。更糟糕的是,当JSF项目阶段设置为Production时,没有任何视觉反馈,并且服务器日志不显示有关异常的任何信息。 如果相关,那么我在Netbeans中使用GlassFish。 问题答案: OmniFaces

  • Spring MVC 3.2开始引入了基于Servlet 3的异步请求处理。相比以前,控制器方法已经不一定需要返回一个值,而是可以返回一个java.util.concurrent.Callable的对象,并通过Spring MVC所管理的线程来产生返回值。与此同时,Servlet容器的主线程则可以退出并释放其资源了,同时也允许容器去处理其他的请求。通过一个TaskExecutor,Spring M

  • 问题内容: 它在DEBUG = True模式下运行。有时,当遇到错误时,它可能会抛出带有追溯信息的错误消息,但有时,它仅显示以下行: 我必须切换到开发服务器才能查看详细消息。 遇到错误时,如何使它始终显示回溯消息? 问题答案: 也许你可以使用此代码段,这会将异常记录在apache的日志中: 把它放在你的settings.py: 在你的代码中: