I've got asp.net core webapi app which currently uses Microsoft.AspNetCore.Identity and services.AddDbContext in ConfigureServices methods in Startup class and everything works so far.
I tried to use services.AddPooledDbContextFactory instead of services.AddDbContext to improve performance. However when I try to use AddPooledDbContextFactory I've got an error:
System.InvalidOperationException: Unable to resolve service for type
'hostapp.Data.DataContext' while attempting to activate
'Microsoft.AspNetCore.Identity.EntityFrameworkCore.RoleStore5[hostapp.Models.AppRole,hostapp.Data.DataContext,System.Int32,hostapp.Models.AppUserRole,Microsoft.AspNetCore.Identity.IdentityRoleClaim1[System.Int32]]'
After seeing this error I created new webapi project which uses AddPooledDbContextFactory without Microsoft.AspNetCore.Identity which works fine. So my question is:
What is the proper way of using services.AddPooledDbContextFactory with Microsoft.AspNetCore.Identity to avoid error above?
in ProjectRoot/Startup.cs
using System.Threading.Tasks;
using hostapp.Data;
using hostapp.GraphQL;
using hostapp.Interfaces;
using hostapp.Models;
using hostapp.Services;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace hostapp
{
public class Startup
{
// ...
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<ICookieService, CookieService>();
// EARLIER IMPLEMENTATION WHICH WORKS FINE =>
// services.AddDbContext<DataContext>(options =>
// {
// options.UseSqlServer(_config.GetConnectionString("DefaultConnection"));
// });
// CURRENT IMPLEMENTATION WHICH CAUSES AN ERROR
services.AddPooledDbContextFactory<DataContext>(options =>
{
options.UseSqlServer(_config.GetConnectionString("DefaultConnection"));
});
services.AddIdentityCore<AppUser>(opt =>
{
opt.Password.RequireNonAlphanumeric = false;
})
.AddRoles<AppRole>()
.AddRoleManager<RoleManager<AppRole>>()
.AddSignInManager<SignInManager<AppUser>>()
.AddRoleValidator<RoleValidator<AppRole>>()
.AddEntityFrameworkStores<DataContext>();
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.Cookie.Name = "app-cookie";
// options.Cookie.Expiration = TimeSpan.FromMinutes(30);
options.Events.OnRedirectToLogin = context =>
{
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
return Task.CompletedTask;
};
});
services.AddAuthorization(opt =>
{
opt.AddPolicy("RequireAdminRole", policy => policy.RequireRole("Admin"));
});
services
.AddGraphQLServer()
.AddAuthorization()
.AddQueryType<Query>();
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors(options => options
.AllowAnyHeader()
.AllowAnyMethod()
.WithOrigins("https://localhost:4200")
.SetIsOriginAllowed(origin => true)
.AllowCredentials());
app.UseCookiePolicy(new CookiePolicyOptions
{
MinimumSameSitePolicy = SameSiteMode.Strict,
// HttpOnly = Microsoft.AspNetCore.CookiePolicy.HttpOnlyPolicy.Always,
// Secure = CookieSecurePolicy.Always
});
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapGraphQL();
});
}
}
}
in ProjectRoot/Data/DataContext.cs
using hostapp.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
namespace hostapp.Data
{
public class DataContext : IdentityDbContext<AppUser, AppRole, int,
IdentityUserClaim<int>, AppUserRole, IdentityUserLogin<int>,
IdentityRoleClaim<int>, IdentityUserToken<int>>
{
public DataContext(DbContextOptions<DataContext> options) : base(options)
{
}
public DbSet<AppUserClaim> Claims { get; set; }
public DbSet<AppUserClaimOffender> Offenders { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<AppUser>()
.HasMany(ur => ur.AppUserRoles)
.WithOne(u => u.AppUser)
.HasForeignKey(ur => ur.UserId)
.IsRequired();
builder.Entity<AppRole>()
.HasMany(ur => ur.AppUserRoles)
.WithOne(u => u.AppRole)
.HasForeignKey(ur => ur.RoleId)
.IsRequired();
}
}
}
in ProjectRoot/app.csproj
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.Cookies" Version="2.2.0"/>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="5.0.0" NoWarn="NU1605"/>
<PackageReference Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" Version="5.0.0" NoWarn="NU1605"/>
<PackageReference Include="Swashbuckle.AspNetCore" Version="5.6.3"/>
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="5.0.0"/>
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="5.0.0"/>
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="5.0.0"/>
<PackageReference Include="HotChocolate.AspNetCore" Version="11.1.0"/>
<PackageReference Include="HotChocolate.AspNetCore.Authorization" Version="11.1.0"/>
<PackageReference Include="HotChocolate.Data.EntityFramework" Version="11.1.0"/>
<PackageReference Include="Microsoft.AspNetCore.Cors" Version="2.2.0"/>
</ItemGroup>
</Project>
What is the proper way of using services.AddPooledDbContextFactory
with Microsoft.AspNetCore.Identity to avoid error above?
In the ConfigureServices, try to use AddScoped() method to register the DBContext and use the provider to get the factory from the services. Then, return the instance to the provider. The code like this:
services.AddPooledDbContextFactory<DataContext>(options =>
{
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
options.EnableSensitiveDataLogging();
}, poolSize:32);
services.AddScoped<DataContext>(p => p.GetRequiredService<IDbContextFactory<DataContext>>().CreateDbContext());
Related
I'm trying to create my first webjobapp that requires the use of Entity Framework. I am trying to inject my context into the builder of the app, but I'm getting an error:
Cannot bind parameter 'db' to type ApplicationDbContext. Make sure the parameter Type is supported by the binding
There are several examples on the web but the versions of the Azure WebJob appear to have changed quickly and I can't find one that works for the version I'm using. These are the package versions I'm using:
Webjobs 3.0
EF.NET Core 7.0
Targeting .NET 7.0
Here is my code:
class Program
{
static async Task Main()
{
var builder = new HostBuilder();
builder.ConfigureWebJobs(b =>
{
b.AddTimers();
b.AddAzureStorageCoreServices();
});
builder.ConfigureLogging((context, b) =>
{
b.AddConsole();
});
builder.ConfigureAppConfiguration((hostContext, configApp) =>
{
configApp.SetBasePath(Directory.GetCurrentDirectory());
configApp.AddEnvironmentVariables(prefix: "ASPNETCORE_");
configApp.AddJsonFile($"appsettings.json", true);
configApp.AddJsonFile($"appsettings.{hostContext.HostingEnvironment.EnvironmentName}.json", true);
});
builder.ConfigureServices(services => { services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer("My full connection string"));
services.AddTransient<IEmailSender, EmailSender>();
});
var host = builder.Build();
using (host)
//{
await host.RunAsync();
}
}
}
public class Functions
public static void Sendemails([TimerTrigger("0 0 20 * * SUN-THU")] TimerInfo timer,
ILogger logger, ApplicationDbContext db)
{
var mylist = db.Users.ToList();
}
}
I tried to configure the services using the following code instead of the above code. When inspecting the builder I can see that the services were added to the builder. But inspecting the host after the call to builder.Build(), The services do not show up in the host container.
var serviceCollection = new ServiceCollection();
ConfigureServices(serviceCollection);
.....
builder.ConfigureServices((context, sc) => sc= serviceCollection);
var host = builder.Build();
using (host)
{
await host.RunAsync();
}
}
.....
private void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(_configuration.GetConnectionString("DefaultConnection")))
}
Project File
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<None Remove="appsettings.Development.json" />
<None Remove="appsettings.json" />
</ItemGroup>
<ItemGroup>
<Content Include="appsettings.Development.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<ExcludeFromSingleFile>true</ExcludeFromSingleFile>
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
</Content>
<Content Include="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<ExcludeFromSingleFile>true</ExcludeFromSingleFile>
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
</Content>
</ItemGroup>
<ItemGroup>
<PackageReference
Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="7.0.1" />
<PackageReference Include="Microsoft.Azure.WebJobs" Version="3.0.33" />
<PackageReference Include="Microsoft.Azure.WebJobs.Extensions" Version="4.0.1" />
<PackageReference Include="Microsoft.Azure.WebJobs.Extensions.OpenApi.Configuration.AppSettings" Version="1.5.0" />
<PackageReference Include="Microsoft.Azure.WebJobs.Extensions.SendGrid" Version="3.0.2" />
<PackageReference Include="Microsoft.Azure.WebJobs.Extensions.Storage" Version="5.0.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="7.0.1" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="7.0.0" />
<PackageReference Include="SendGrid" Version="9.28.1" />
</ItemGroup>
</Project>
Initially Even I got the same error.
Done few changes in Program.cs .
My Program.cs:
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
class Program
{
static async Task Main()
{
var builder = new HostBuilder()
.ConfigureWebJobs(b =>
{
b.AddTimers();
b.AddAzureStorageCoreServices();
})
.ConfigureLogging((context, b) =>
{
b.AddConsole();
})
.ConfigureAppConfiguration((hostContext, configApp) =>
{
configApp.SetBasePath(Directory.GetCurrentDirectory());
configApp.AddEnvironmentVariables(prefix: "ASPNETCORE_");
configApp.AddJsonFile($"appsettings.json", true);
configApp.AddJsonFile($"appsettings.{hostContext.HostingEnvironment.EnvironmentName}.json", true);
})
.ConfigureServices(services =>
{
services.AddDbContext<ApplicationDbContext>(
options => options.UseSqlServer("MyDefaultConnection"));
services.AddTransient<ApplicationDbContext, ApplicationDbContext>();
});
var host = builder.Build();
using (host)
{
await host.RunAsync();
}
}
}
If you are running locally, cross check the local.settings.json file once.
My local.settings.json :
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"FUNCTIONS_WORKER_RUNTIME": "dotnet"
}
}
My appsettings.json:
{
"ConnectionStrings": {
"AzureWebJobsStorage": "Storage Account Connection String"
}
}
Also have a look at SO Thread once.
References taken from MSDoc.
I do the steps from the beginning.
1-
public class ApplicationDbContext: IdentityDbContext<User, Role, Guid>
{
public ApplicationDbContext(DbContextOptions options)
: base(options)
{
}
}
2-add in appsettings.json
"ConnectionStrings": {
"SqlServer": "Data Source=;Initial Catalog=SpaceManagment;User ID=sa;Password=654321;MultipleActiveResultSets=true;TrustServerCertificate=True;Connection Timeout = 60"
},
3-
add in program.cs
builder.Services.AddDbContext<ApplicationDbContext>(options =>
{
options
.UseSqlServer(settings.SqlServer);
//Tips
// .ConfigureWarnings(warning => warning.Throw(RelationalEventId.QueryClientEvaluationWarning));
});
I am trying to create windows service using dotnet worker project that starts up rest-api, I am using kestrel server for this purpose:
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Builder;
namespace TurkisisService
{
public class Worker : BackgroundService
{
private readonly ILogger<Worker> _logger;
public Worker(ILogger<Worker> logger)
{
_logger = logger;
kestrelStarted=false;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
_logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
if(!kestrelStarted) {
kestrelStarted=true;
var host = new WebHostBuilder()
.UseKestrel()
.UseStartup<Startup>()
.Build();
var task = Task.Run(() => {
host.Run();
});
}
await Task.Delay(1000, stoppingToken);
}
}
private bool kestrelStarted;
}
public class Startup {
public void Configure(IApplicationBuilder app){
app.Run(context => {
return context.Response.WriteAsync("Hello world!");
});
}
}
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<Worker>();
});
}
}
I used these packages:
<Project Sdk="Microsoft.NET.Sdk.Worker">
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
<UserSecretsId>dotnet-turkisis_service-9216353E-18A1-49B4-8CAB-E939439FF992</UserSecretsId>
<RootNamespace>turkisis_service</RootNamespace>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Server.Kestrel" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="5.0.0" />
</ItemGroup>
The console displays these lines of logs:
Now listening on: http://localhost:5000
Now listening on: https://localhost:5001
but when I open the url on web browser: http://localhost:5000, also https://localhost:5001 returns empty, they are display: ERR_EMPTY_RESPONSE
I want to set all localhost port can allow CORS and then i tried to use * keyword to do it , like below code :
readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
public void ConfigureServices(IServiceCollection services)
{
//..
services.AddCors(options =>
{
options.AddPolicy(name: MyAllowSpecificOrigins,
builder =>
{
builder.WithOrigins($"http://localhost:*");
}
);
});
//..
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
//..
app.UseCors(MyAllowSpecificOrigins);
//..
}
but it not work :
csproj :
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp3.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Dapper" Version="2.0.35" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.0.0" />
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
<PackageReference Include="System.Data.SqlClient" Version="4.8.1" />
</ItemGroup>
</Project>
I want to set all localhost port can allow CORS
To achieve above requirement, you can try:
services.AddCors(options =>
{
options.AddPolicy(name: MyAllowSpecificOrigins,
builder =>
{
builder.SetIsOriginAllowed(origin => new Uri(origin).Host == "localhost");
}
);
});
I created a Razor Pages Web App with Authentication set to Individual User Accounts.
I then tried to add IdentityServer4 to the Startup so that I could also support {{base_url}}/connect/token to get an access_token.
When I called {{base_url}}/connect/token I get a 500 error and the console log shows that the Clients table doesn't exist.
I then tried to do an add-migration and I get the error: More than one DbContext was found.
Below is my Startup.cs file... is there something in here that I should fix so that there are not (seemingly) two DbContexts?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using MyIdentityServer.Data;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using MyIdentityServer.Entities;
using MyIdentityServer.Services;
using Microsoft.AspNetCore.Identity.UI.Services;
using MyIdentityServer.IdentityServer;
using System.Reflection;
namespace MyIdentityServer
{
public class Startup
{
public Startup(IWebHostEnvironment environment, IConfiguration configuration)
{
Environment = environment;
Configuration = configuration;
}
public IWebHostEnvironment Environment { get; }
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
var connectionString = Configuration.GetConnectionString("DefaultConnection");
string migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(connectionString));
services.AddIdentity<ApplicationUser, IdentityRole>(config =>
{
config.SignIn.RequireConfirmedEmail = false;
})
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
var builder = services.AddIdentityServer(options =>
{
options.Events.RaiseErrorEvents = true;
options.Events.RaiseInformationEvents = true;
options.Events.RaiseFailureEvents = true;
options.Events.RaiseSuccessEvents = true;
options.EmitStaticAudienceClaim = true;
})
// .AddInMemoryPersistedGrants()
/*
.AddInMemoryIdentityResources(IdentityServerConfig.IdentityResources)
.AddInMemoryApiScopes(IdentityServerConfig.ApiScopes)
.AddInMemoryClients(IdentityServerConfig.Clients)
*/
.AddConfigurationStore(options =>
{
options.ConfigureDbContext = builder => builder.UseSqlServer(connectionString, sql => sql.MigrationsAssembly(migrationsAssembly));
})
.AddOperationalStore(options =>
{
options.ConfigureDbContext = builder => builder.UseSqlServer(connectionString, sql => sql.MigrationsAssembly(migrationsAssembly));
options.EnableTokenCleanup = true; // this enables automatic token cleanup. this is optional.
options.TokenCleanupInterval = 30;
})
.AddAspNetIdentity<ApplicationUser>();
services.Configure<SmtpSettings>(Configuration.GetSection("SmtpSettings"));
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();
services.AddScoped<IDecryptCookieService, DecryptCookieService>();
services.AddAuthentication()
.AddFacebook(facebookOptions =>
{
facebookOptions.AppId = Configuration["Authentication:Facebook:AppId"];
facebookOptions.AppSecret = Configuration["Authentication:Facebook:AppSecret"];
facebookOptions.AccessDeniedPath = "/AccessDeniedPathInfo";
})
.AddTwitter(twitterOptions =>
{
twitterOptions.ConsumerKey = Configuration["Authentication:Twitter:ConsumerAPIKey"];
twitterOptions.ConsumerSecret = Configuration["Authentication:Twitter:ConsumerSecret"];
twitterOptions.RetrieveUserDetails = true;
});
services.AddControllersWithViews();
services.AddRazorPages();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/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.UseIdentityServer();
app.UseAuthentication();
app.UseAuthorization(); // <- allows the use of [Authorize] on controllers and action
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapRazorPages();
});
}
}
}
Also, in the Data folder:
using System;
using System.Collections.Generic;
using System.Text;
using MyIdentityServer.IdentityServer;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
namespace MyIdentityServer.Data
{
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
}
}
and
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
namespace MyIdentityServer.IdentityServer
{
public class ApplicationUser : IdentityUser
{
}
}
Ok... so it turns out that IdentityServer4 (when implemented as above) does add two additional contexts:
// add-migration -context ApplicationDbContext
// add-migration -context PersistedGrantDbContext
// add-migration -context ConfigurationDbContext
I am getting the below error :
InvalidOperationException: No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider. If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions object in its constructor and passes it to the base constructor for DbContext.
Startup.cs :
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddDistributedMemoryCache();
services.AddSession(options=>{options.IdleTimeout = TimeSpan.FromMinutes(1);});services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options =>
{
options.Cookie.HttpOnly = true;
options.ExpireTimeSpan = TimeSpan.FromMinutes(20);
options.Cookie.Name = "SampleCore";
options.LoginPath = "/log-in";
//options.AccessDeniedPath = "/access-denied";
options.LogoutPath = "/log-off";
options.ReturnUrlParameter = "postBack";
});
services.AddMvc(options =>
{
options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute());
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
string connection = Configuration.GetConnectionString("MyConnection");
services.AddDbContext<EmployeeContext>(options => options.UseSqlServer(connection), ServiceLifetime.Scoped);
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseStaticFiles();
app.UseSession();
app.UseCookiePolicy();
app.UseAuthentication();
app.UseCustomErrorPages();
app.UseMvc();
}
UseCustomErrorPages Extension :
public async Task Invoke(HttpContext context)
{
await _next(context); // Getting error at this line
if (context.Response.StatusCode == 404 && !context.Response.HasStarted)
{
string originalPath = context.Request.Path.Value;
context.Items["originalPath"] = originalPath;
context.Request.Path = "/page-not-found";
await _next(context);
}
else if (context.Response.StatusCode == 500)
{
string originalPath = context.Request.Path.Value;
context.Items["originalPath"] = originalPath;
context.Request.Path = "/error";
await _next(context);
}
else if(context.Response.StatusCode == 401)
{
string originalPath = context.Request.Path.Value;
context.Items["originalPath"] = originalPath;
context.Request.Path = "/access-denied";
await _next(context);
}
}
DbContext :
public partial class EmployeeContext : DbContext
{
public EmployeeContext(DbContextOptions<EmployeeContext> options)
: base(options)
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
var connectionString = "connectionString";
optionsBuilder.UseSqlServer(connectionString);
base.OnConfiguring(optionsBuilder);
}
}
public virtual DbSet<TblEmployee> TblEmployee { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
//Code
}
}
csproj file :
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.1.2" PrivateAssets="All" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.1.4" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.1.4" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer.Design" Version="1.1.6" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.1.4">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.1.6" />
Controller :
private EmployeeContext _context;
public HomeController(EmployeeContext context)
{
_context = context;
}
public List<TblEmployee> GetEmployees
{
List<TblEmployee> getEmployees = _context.TblEmployee.ToList();
return getEmployees ;
}
appsettings.json :
{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"ConnectionStrings": {
"MyConnection": "connection string"
},
"AllowedHosts": "*"
}
I don't understand where I did wrong. Kindly help