Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/282.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在ASP.NET Core 3.1的Startup.cs中注入服务_C#_Asp.net Core 3.1 - Fatal编程技术网

C# 在ASP.NET Core 3.1的Startup.cs中注入服务

C# 在ASP.NET Core 3.1的Startup.cs中注入服务,c#,asp.net-core-3.1,C#,Asp.net Core 3.1,我正在开发一个.NETCore3.1应用程序。我需要在Startup.cs中注入服务。我的代码是: Program.cs: public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateH

我正在开发一个.NETCore3.1应用程序。我需要在Startup.cs中注入服务。我的代码是:

Program.cs:

public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureServices(servicesCollection =>
                {
                    servicesCollection.AddScoped<IUnauthorizedAccessService, UnauthorizedAccessService>();
                })
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }
运行代码时,会出现以下异常:

Unable to resolve service for type 'Interface.Service.IUnauthorizedAccessService' while attempting to activate 'Website.Startup'.'
如何在Startup.cs中注入服务?我甚至尝试过进入
Configure
方法。但是,我得到了存储库级别的异常。代码:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IUnauthorizedAccessService unauthorizedAccessService)
        {
            _unauthorizedAccessService = unauthorizedAccessService;

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                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.UseSession();
            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();
            app.UseCookiePolicy(new CookiePolicyOptions
            {
                MinimumSameSitePolicy = SameSiteMode.Strict,
            });

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=User}/{action=Index}/{id?}");
            });
        }
我有一个方法
RegisterDatabase
,它是从
ConfigureServices
调用的。代码:

private void RegisterDatabase(IServiceCollection services)
        {
            services.AddDbContext<TrainingContext>(options =>
                    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
        }
我的所有其他存储库都在工作,但只有在这一点上才会出现异常。可能的问题是什么?任何帮助都将不胜感激

基本上,我试图实现的是,我想在数据库中记录对我的站点的未经授权的访问。代码是:

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                .AddCookie(o =>
                {
                    o.AccessDeniedPath = "/Home/Error";
                    o.LoginPath = "/Login";
                    o.SlidingExpiration = false;
                    o.Events = new CookieAuthenticationEvents
                    {
                        //OnRedirectToAccessDenied = new Func<RedirectContext<CookieAuthenticationOptions>, Task>(context =>

                        OnRedirectToAccessDenied = new Func<RedirectContext<CookieAuthenticationOptions>, Task>(test)
                    };
                });
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(o=>
{
o、 AccessDeniedPath=“/Home/Error”;
o、 LoginPath=“/Login”;
o、 slidengexpiration=false;
o、 事件=新CookieAuthenticationEvents
{
//OnRedirectToAccessDenied=新函数(上下文=>
OnRedirectToAccessDenied=新函数(测试)
};
});
试验方法为:

private async Task<Task> test (RedirectContext<CookieAuthenticationOptions> context)
        {
            string user = context.HttpContext.User.Identity.Name;
            string url = "/" + context.Request.Host.Value + "/" + context.Request.RouteValues["controller"] + "/" + context.Request.RouteValues["action"];
            string sessionId = context.HttpContext.Session.Id;

            await _unauthorizedAccessService.LogUnauthorizedAccessInDB(user, url, sessionId);

            context.Response.Redirect("/Home/Error");
            return context.Response.CompleteAsync();
        }
专用异步任务测试(重定向上下文)
{
字符串user=context.HttpContext.user.Identity.Name;
字符串url=“/”+context.Request.Host.Value+“/”+context.Request.RouteValues[“controller”]+“/”+context.Request.RouteValues[“action”];
字符串sessionId=context.HttpContext.Session.Id;
wait_unauthorizedAccessService.LogUnauthorizedAccessInDB(用户、url、会话ID);
Redirect(“/Home/Error”);
返回context.Response.CompleteAsync();
}

Startup.cs
是为配置自己的服务和管道配置而设计的。您不能将自定义服务注入构造函数,因为它们尚未配置

文件:

主机提供启动类可用的服务 构造函数。应用程序通过ConfigureServices添加其他服务。 主机和应用程序服务都可在配置中使用和 整个应用程序


Startup.cs
是为配置自己的服务和管道配置而设计的。您不能在构造函数中注入自定义服务,因为它们尚未配置

文件:

主机提供启动类可用的服务 构造函数。应用程序通过ConfigureServices添加其他服务。 主机和应用程序服务都可在配置中使用和 整个应用程序


您需要创建实现
CookieAuthenticationEvents
的作用域对象。例如:

使用Microsoft.AspNetCore.Authentication;
使用Microsoft.AspNetCore.Authentication.Cookies;
使用System.Threading.Tasks;
名称空间MyApplication.Services
{
公共类MyCookieAuthenticationEvents:CookieAuthenticationEvents
{
私有只读IUnauthorizedAccessService(未经授权的数据访问服务);
公共MyCokieAuthenticationEvents(
IUnauthorizedAccessService(未授权的数据访问服务)
{
_unauthorizedAccessService=unauthorizedAccessService;
}
公共覆盖任务重定向到拒绝访问(
重定向(上下文)
{
//TODO:您可以在此处使用未经授权的访问服务
返回base.RedirectToAccessDenied(上下文);
}
}
}
要注入此内容,您可以这样做:

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(选项=>
{
options.EventsType=typeof(mycokieeauthenticationevents);
});
services.addScope();
services.addScope();
确保从
程序.cs
中删除该
IUnauthorizedAccessService
。您不在那里注入。而是注入
Configure
方法


这就是正确的依赖项注入的方式。你不做公认答案正在做的事情。这可能是我很久以来见过的最不正统的事情之一。

你需要创建一个作用域对象来实现
CookieAuthenticationEvents
。例如:

使用Microsoft.AspNetCore.Authentication;
使用Microsoft.AspNetCore.Authentication.Cookies;
使用System.Threading.Tasks;
名称空间MyApplication.Services
{
公共类MyCookieAuthenticationEvents:CookieAuthenticationEvents
{
私有只读IUnauthorizedAccessService(未经授权的数据访问服务);
公共MyCokieAuthenticationEvents(
IUnauthorizedAccessService(未授权的数据访问服务)
{
_unauthorizedAccessService=unauthorizedAccessService;
}
公共覆盖任务重定向到拒绝访问(
重定向(上下文)
{
//TODO:您可以在此处使用未经授权的访问服务
返回base.RedirectToAccessDenied(上下文);
}
}
}
要注入此内容,您可以这样做:

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(选项=>
{
options.EventsType=typeof(mycokieeauthenticationevents);
});
services.addScope();
services.addScope();
确保从
程序.cs
中删除该
IUnauthorizedAccessService
。您不在那里注入。而是注入
Configure
方法


这就是正确的依赖注入的方式。你不做公认答案所做的事情。这可能是我很久以来见过的最不正统的事情之一。

管道还没有建立起来
Cannot access a disposed context instance. A common cause of this error is disposing a context instance that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling 'Dispose' on the context instance, or wrapping it in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances.
Object name: 'TrainingContext'.
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                .AddCookie(o =>
                {
                    o.AccessDeniedPath = "/Home/Error";
                    o.LoginPath = "/Login";
                    o.SlidingExpiration = false;
                    o.Events = new CookieAuthenticationEvents
                    {
                        //OnRedirectToAccessDenied = new Func<RedirectContext<CookieAuthenticationOptions>, Task>(context =>

                        OnRedirectToAccessDenied = new Func<RedirectContext<CookieAuthenticationOptions>, Task>(test)
                    };
                });
private async Task<Task> test (RedirectContext<CookieAuthenticationOptions> context)
        {
            string user = context.HttpContext.User.Identity.Name;
            string url = "/" + context.Request.Host.Value + "/" + context.Request.RouteValues["controller"] + "/" + context.Request.RouteValues["action"];
            string sessionId = context.HttpContext.Session.Id;

            await _unauthorizedAccessService.LogUnauthorizedAccessInDB(user, url, sessionId);

            context.Response.Redirect("/Home/Error");
            return context.Response.CompleteAsync();
        }