RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / user-445352

AofA Group's questions

Martin Hope
AofA Group
Asked: 2024-01-20 03:55:38 +0000 UTC

如何禁用 EF Core (.net core) 数据库日志记录

  • 5

为了使用数据库,我使用 ORM Entity Framework Core。启动应用程序后,对数据库的所有请求都会记录在控制台中。我没有安装日志记录。如何禁用它?

程序.cs:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddHangfire(x => x.UseSqlServerStorage(builder.Configuration.GetConnectionString("DefaultConnection")));
builder.Services.AddHangfireServer(opt =>
{
    opt.StopTimeout = TimeSpan.FromMinutes(5);
});
builder.Services.AddControllers();
builder.Services.AddSwaggerGen();
builder.Services.AddAutoMapper(typeof(AutoMapperConf));

builder.Services.AddCors(o => o.AddDefaultPolicy(builder =>
{
    builder
    .WithOrigins("http://localhost:80")
    .AllowCredentials()
    .AllowAnyHeader()
    .AllowAnyMethod();
}));

// DB Services
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");

builder.Services.AddDbContext<AMContext>(options => options.UseSqlServer(connectionString), ServiceLifetime.Transient);
builder.Services.AddDbContext<AMIdentityContext>(options => options.UseSqlServer(connectionString), ServiceLifetime.Transient);

builder.Services.ConfigureApplicationCookie(opt =>
{
    opt.LoginPath = "/auth/login";
    opt.LogoutPath = "/auth/logut";
    opt.AccessDeniedPath = "/";
    opt.ExpireTimeSpan = TimeSpan.FromDays(180);
});

builder.Services.AddIdentity<DBUser, IdentityRole>(config =>
{
    config.Password.RequireNonAlphanumeric = false;
    config.Password.RequiredLength = 1;
    config.Password.RequireUppercase = false;
    config.Password.RequireDigit = false;
    config.Password.RequireLowercase = false;
})
    .AddEntityFrameworkStores<AMIdentityContext>()
    .AddDefaultTokenProviders();

builder.Services.AddSpaStaticFiles(configuration =>
{
    configuration.RootPath = "wwwroot";
});
var app = builder.Build();

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

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseCors();
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseHangfireDashboard("/hangfire", new DashboardOptions
{
    Authorization = new[] { new HangfireAuthFilter() }
});

app.MapControllers();
app.UseEndpoints(endpoints =>
{
    endpoints.MapDefaultControllerRoute();
});

app.UseSpa(spa =>
{
    spa.Options.SourcePath = "ClientApp";
    if (app.Environment.IsDevelopment())
    {
        spa.UseAngularCliServer(npmScript: "start");
        spa.UseProxyToSpaDevelopmentServer("http://localhost:4200");
    }
});


RecurringJob.AddOrUpdate<HangFireTaskManager>("TaskParser", (method) => method.TaskParser(), "*/1 * * * * *");
RecurringJob.AddOrUpdate<HangFireTaskManager>("PostParser", (method) => method.PostParser(), "*/1 * * * * *");
RecurringJob.AddOrUpdate<HangFireTaskManager>("MonitorStatus", (method) => method.MonitorStatus(), "*/1 * * * * *");
RecurringJob.AddOrUpdate<HangFireTaskManager>("CommentParser", (method) => method.CommentParser(), "*/1 * * * * *");
RecurringJob.AddOrUpdate<HangFireTaskManager>("LikesParser", (method) => method.LikesParser(), "*/1 * * * * *");


// Init Roles
using (var scope = app.Services.CreateScope())
{
    var services = scope.ServiceProvider;
    try
    {
        var rolesManager = services.GetRequiredService<RoleManager<IdentityRole>>();
        await RoleInitializer.InitializeAsync(rolesManager);
    }
    catch (Exception ex)
    {
        var logger = services.GetRequiredService<ILogger<Program>>();
        logger.LogError(ex, "An error occurred while seeding the database.");
    }
}

app.Run();
asp.net-core
  • 1 个回答
  • 22 Views
Martin Hope
AofA Group
Asked: 2022-08-29 23:05:32 +0000 UTC

AggregateException:无法构造某些服务 - c#。初始化项目时出错

  • 1

大家好。我正在重写项目的架构,当我完成时,我收到了这个错误:

"AggregateException: Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: Implemantation.IServices.IOrderService Lifetime: Transient ImplementationType: Implemantation.Services.OrderService': Unable to resolve service for type 'DBInfrastructure.TRepository`1[DBInfrastructure.DTOModels.OrderModel]' while attempting to activate 'Implemantation.Services.OrderService'.)"

"InvalidOperationException: Error while validating the service descriptor 'ServiceType: Implemantation.IServices.IOrderService Lifetime: Transient ImplementationType: Implemantation.Services.OrderService': Unable to resolve service for type 'DBInfrastructure.TRepository`1[DBInfrastructure.DTOModels.OrderModel]' while attempting to activate 'Implemantation.Services.OrderService'."

"AggregateException: Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: Implemantation.IServices.IOrderService Lifetime: Transient ImplementationType: Implemantation.Services.OrderService': Unable to resolve service for type 'DBInfrastructure.TRepository`1[DBInfrastructure.DTOModels.OrderModel]' while attempting to activate 'Implemantation.Services.OrderService'.)"

这是斯图普:

public void ConfigureServices(IServiceCollection services)
        {
            services.AddTransient<TRepository<OrderModel>, OrderRepository>();

            services.AddTransient<IOrderService, OrderService>();
        }

这是订单服务:

public class OrderService : IOrderService
    {
        public readonly Random Randomizer = new();
        private readonly TRepository<OrderModel> orderRepository;

        public OrderService(TRepository<OrderModel> orderRepository)
        {
            this.orderRepository = orderRepository;
        }
    }

这是 TRepository:

public class TRepository<T> : IRepository<T> where T : class
    {
        public ISchema Schema { get; set; }
        public ISpace Space { get; set; }
        public IIndex PrimaryIndex { get; set; }
        protected Box box { get; set; }
        private bool disposedValue;

        public  TRepository( Box box, string vspace, string viindex)
        {
            this.box = box;
            _ = Init(vspace, viindex);
        } // ctor
        private async Task Init(string vspace, string viindex)
        {
            Schema = box.GetSchema();
            Space = await box.GetSchema().GetSpace(vspace);
            PrimaryIndex = await Space.GetIndex(viindex);
        } // init func
    }

这是 IRepository:

public interface IRepository<T> : IDisposable where T: class
    {
        public T FindById<Y>(Y id);
        public IEnumerable<T> FindAll();
        public Task Create(T model);
        public Task Delete(T model);
        public Task Update(T moodel);
    }

这是 OrderRepository:

public class OrderRepository : TRepository<OrderModel>
    {
        public OrderRepository(Box box) : base(box, vspace, viindex) { }

        private readonly static string vspace = "orders";
        private readonly static string viindex = "primary_index";
    }

启动 Web 应用程序时发生错误。这是错误的屏幕截图: 错误截图

c#
  • 1 个回答
  • 10 Views
Martin Hope
AofA Group
Asked: 2022-08-09 21:18:39 +0000 UTC

如何将 1 个对象而不是其几个属性传递给函数?c# [关闭]

  • 0
关闭 这个问题是题外话。目前不接受回复。

寻求调试帮助的问题(“为什么这段代码不起作用? ”)应该包括期望的行为、具体的问题或错误,以及在问题中重现它的最少代码。没有明确描述问题的问题对其他访问者毫无用处。请参阅如何创建一个最小的、独立的和可重现的示例。

1 年前关闭。

改进问题

大家好。我有这行代码:

 await space.Insert(TarantoolTuple.Create(model.Id, model.Login, model.Balance));

在那里,您需要通过“,”传递插入数据库所需的必要参数。
所有这些参数都是模型对象的属性。
但是,如果我在那里传递对象本身,则不会执行该操作。

public async Task<UserModel> Insert(UserModel model)
        {
            model.Id = Guid.NewGuid().ToString();
            await space.Insert(TarantoolTuple.Create(model));
            return model;
        }

如何解决这个问题?
这个函数稍后会被概括,并且不希望每个实例只为这个函数规定所有属性。

c#
  • 2 个回答
  • 10 Views
Martin Hope
AofA Group
Asked: 2022-06-12 23:06:25 +0000 UTC

由于 Hangfire,升级后无法启动网络服务器

  • 0

大家好。新更新后,我无法启动网络。常规 IIS 中的应用程序。这是我得到的错误:

HTTP Error 500.30 - ANCM In-Process Start Failure

日志:

Unhandled exception. System.IO.FileNotFoundException: Could not load file or assembly 'Hangfire.Core, Version=1.7.23.0, Culture=neutral, PublicKeyToken=null'. Не удается найти указанный файл.

File name: 'Hangfire.Core, Version=1.7.23.0, Culture=neutral, PublicKeyToken=null'

   at SMSServicePanel.Startup.ConfigureServices(IServiceCollection services)

   at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)

   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)

   at Microsoft.AspNetCore.Hosting.ConfigureServicesBuilder.InvokeCore(Object instance, IServiceCollection services)

   at Microsoft.AspNetCore.Hosting.ConfigureServicesBuilder.<>c__DisplayClass9_0.<Invoke>g__Startup|0(IServiceCollection serviceCollection)

   at Microsoft.AspNetCore.Hosting.ConfigureServicesBuilder.Invoke(Object instance, IServiceCollection services)

   at Microsoft.AspNetCore.Hosting.ConfigureServicesBuilder.<>c__DisplayClass8_0.<Build>b__0(IServiceCollection services)

   at Microsoft.AspNetCore.Hosting.GenericWebHostBuilder.UseStartup(Type startupType, HostBuilderContext context, IServiceCollection services)

   at Microsoft.AspNetCore.Hosting.GenericWebHostBuilder.<>c__DisplayClass12_0.<UseStartup>b__0(HostBuilderContext context, IServiceCollection services)

   at Microsoft.Extensions.Hosting.HostBuilder.CreateServiceProvider()

   at Microsoft.Extensions.Hosting.HostBuilder.Build()

   at SMSServicePanel.Program.Main(String[] args) in C:\Users\DELL\Desktop\Исходники проекта SMSServicePanel\SMSServicePanel\Program.cs:line 21

在 VS 上的 IIS Express 中一切正常,它不想在服务器上运行。可能是什么问题呢?

c#
  • 1 个回答
  • 10 Views
Martin Hope
AofA Group
Asked: 2022-06-11 07:16:49 +0000 UTC

挂火任务不工作[关闭]

  • 0
关闭 这个问题是题外话。目前不接受回复。

该问题是由不再复制的问题或错字引起的。虽然类似的问题可能与本网站相关,但该问题的解决方案不太可能帮助未来的访问者。通常可以通过在发布问题之前编写和研究一个最小程序来重现问题来避免此类问题。

1 年前关闭。

改进问题

大家好。我最近不得不使用hangfire 来启动某个任务。

启动任务时,调度程序本身出现以下异常:

Failed
An exception occurred during processing of a background job.

System.InvalidOperationException
A suitable constructor for type 'SMSServicePanel.GetInfoForResourseService' could not be located. Ensure the type is concrete and services are registered for all parameters of a public constructor.

System.InvalidOperationException: A suitable constructor for type 'SMSServicePanel.GetInfoForResourseService' could not be located. Ensure the type is concrete and services are registered for all parameters of a public constructor.
   at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.CreateInstance(IServiceProvider provider, Type instanceType, Object[] parameters)
   at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetServiceOrCreateInstance(IServiceProvider provider, Type type)
   at Hangfire.AspNetCore.AspNetCoreJobActivatorScope.Resolve(Type type)
   at Hangfire.Server.CoreBackgroundJobPerformer.Perform(PerformContext context)
   at Hangfire.Server.BackgroundJobPerformer.<>c__DisplayClass9_0.<PerformJobWithFilters>b__0()
   at Hangfire.Server.BackgroundJobPerformer.InvokePerformFilter(IServerFilter filter, PerformingContext preContext, Func`1 continuation)
   at Hangfire.Server.BackgroundJobPerformer.<>c__DisplayClass9_1.<PerformJobWithFilters>b__2()
   at Hangfire.Server.BackgroundJobPerformer.PerformJobWithFilters(PerformContext context, IEnumerable`1 filters)
   at Hangfire.Server.BackgroundJobPerformer.Perform(PerformContext context)
   at Hangfire.Server.Worker.PerformJob(BackgroundProcessContext context, IStorageConnection connection, String jobId)

这是整个任务的代码:

public class jsonserialize
{
    public string name { get; set; }
    public string count { get; set; }
}
public class GetInfoForResourseService
{
    public EFUserDBContext db;
    public IInfoWithPanelRepository infoWithPanelRepository;
    GetInfoForResourseService(EFUserDBContext db, IInfoWithPanelRepository infoWithPanelRepository)
    {
        this.db = db;
        this.infoWithPanelRepository = infoWithPanelRepository;
    }
    private async Task<String> Request()
    {
        var appSettingsJson = AppSettingsJson.GetAppSettings();
        var ip = appSettingsJson["SMSServiceIP"];
        var apikey = appSettingsJson["ApiKeySMSService"];
        WebRequest request = WebRequest.Create($"http://{ip}/stubs/monitors_ajax.php");
        request.Method = "POST"; // для отправки используется метод Post
                                 // данные для отправки
        string data = $"api_key={apikey}";
        // преобразуем данные в массив байтов
        byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(data);
        // устанавливаем тип содержимого - параметр ContentType
        request.ContentType = "application/x-www-form-urlencoded";
        // Устанавливаем заголовок Content-Length запроса - свойство ContentLength
        request.ContentLength = byteArray.Length;

        //записываем данные в поток запроса
        using (Stream dataStream = request.GetRequestStream())
        {
            dataStream.Write(byteArray, 0, byteArray.Length);
        }

        WebResponse response = await request.GetResponseAsync();
        Stream stream = response.GetResponseStream();
        StreamReader reader = new StreamReader(stream);
        string result = reader.ReadToEnd();
        response.Close();
        return result;
    }
    public async Task GetInfo()
    {
        var jsonstring = await Request();
        Root result = JsonConvert.DeserializeObject<Root>(jsonstring);
        var resourselist = new List<jsonserialize>();
        foreach (var item in result.unprocessed_requests)
        {
            var addedItem = new jsonserialize() { name = item.server_name, count = item.requests_count };
            resourselist.Add(addedItem);
        }
        var json = System.Text.Json.JsonSerializer.Serialize(resourselist);
        InfoWithPanel info = await db.Infos.FirstOrDefaultAsync();
        if (info == null)
        {
            var addedinfo = new InfoWithPanel() { Resourses = json, LastUpdate = DateTime.Now };
            infoWithPanelRepository.Create(addedinfo);
        }
        else
        {
            var updatedinfo = new InfoWithPanel() { id = info.id, Resourses = json, LastUpdate = DateTime.Now };
            infoWithPanelRepository.Update(updatedinfo);
        }
        return;
    }
}

}

可能是什么问题呢? 在此处输入图像描述

c#
  • 1 个回答
  • 10 Views
Martin Hope
AofA Group
Asked: 2022-06-11 00:22:56 +0000 UTC

代码未在某行执行

  • 0

大家好。我无法弄清楚为什么代码没有被执行。通过某一行后,跳过其余代码,页面加载成功。

        var json = System.Text.Json.JsonSerializer.Serialize(resourselist);
        InfoWithPanel info = await db.Infos.FirstOrDefaultAsync();
//этот код не выполняется
            if (info == null)
            {
                var addedinfo = new InfoWithPanel() { Resourses = json, LastUpdate = DateTime.Now };
                infoWithPanelRepository.Create(addedinfo);
            }
            else
            {
                var updatedinfo = new InfoWithPanel() { id = info.id, Resourses = json, LastUpdate = DateTime.Now };
                infoWithPanelRepository.Update(updatedinfo);
            }
// этот код не выполняется

未执行的代码以斜体标记。这是调试 GIF:在此处输入图像描述

这是整个方法的屏幕截图。i.imgur.com/edu2PTL.png

c#
  • 2 个回答
  • 10 Views

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    我看不懂措辞

    • 1 个回答
  • Marko Smith

    请求的模块“del”不提供名为“default”的导出

    • 3 个回答
  • Marko Smith

    "!+tab" 在 HTML 的 vs 代码中不起作用

    • 5 个回答
  • Marko Smith

    我正在尝试解决“猜词”的问题。Python

    • 2 个回答
  • Marko Smith

    可以使用哪些命令将当前指针移动到指定的提交而不更改工作目录中的文件?

    • 1 个回答
  • Marko Smith

    Python解析野莓

    • 1 个回答
  • Marko Smith

    问题:“警告:检查最新版本的 pip 时出错。”

    • 2 个回答
  • Marko Smith

    帮助编写一个用值填充变量的循环。解决这个问题

    • 2 个回答
  • Marko Smith

    尽管依赖数组为空,但在渲染上调用了 2 次 useEffect

    • 2 个回答
  • Marko Smith

    数据不通过 Telegram.WebApp.sendData 发送

    • 1 个回答
  • Martin Hope
    Alexandr_TT 2020年新年大赛! 2020-12-20 18:20:21 +0000 UTC
  • Martin Hope
    Alexandr_TT 圣诞树动画 2020-12-23 00:38:08 +0000 UTC
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5