Ambiguity between 'Startup.Configuration' and 'Startup.Configuration' - c#

I get an error of "Ambiguity between 'Startup.Configuration' and 'Startup.Configuration'" on my startup class. I don't know what I have done to cause this issue. All I did was create a DBContext class and this error occured. Please see my code below:
Startup.cs
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SpaServices.AngularCli;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Identity;
using System;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using IssueTracker.Data;
namespace IssueTracker
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
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)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
// In production, the Angular files will be served from this directory
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/dist";
});
// Enabling CORS
services.AddCors(options =>
{
options.AddPolicy("EnableCORS", builder =>
{
builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod().AllowCredentials().Build();
});
});
// Connect to the Database
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.getConnectionString("DefaultConnection")));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
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.UseCors("EnableCORS");
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseSpaStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action=Index}/{id?}");
});
app.UseSpa(spa =>
{
// To learn more about options for serving an Angular SPA from ASP.NET Core,
// see https://go.microsoft.com/fwlink/?linkid=864501
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment())
{
spa.UseAngularCliServer(npmScript: "start");
}
});
}
}
}
ApplicationDbContext
using IssueTracker.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
namespace IssueTracker.Data
{
public class ApplicationDbContext : IdentityDbContext<IdentityUser>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) {}
// Creating the roles
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<IdentityRole>().HasData(
new { Id = "1", name="Admin", NoralizeName = "ADMIN" },
new { Id = "1", name="Customer", NoralizeName = "CUSTOMER" },
new { Id = "1", name="Moderator", NoralizeName = "MODERATOR" }
);
}
public DbSet<ProductModel> Products { get; set; }
}
}
Could you please tell me what is wrong here? Thank you.

I had the same error and simply closing and reopening my IDE (Visual Studio Code) solved it. I hope it helps

One reason for this error might be that you have accidently made a copy of Startup.cs file.

I coppied solution file for backup purposes then I got that error. When I delete the backup file problem solved.

Related

I cant create a migration in asp.net core because i keep getting cant construct db context and im using 2 contexts

I cant create a migration in asp.net core because i keep getting cant construct db context and im using 2 contexts. Ive tried everything to try and fix this but I still cant create migrations because it says it has an error constructing db context and all my code is fine and I cant find out why this wont work. Can someone please help, Thanks.
ApplicationDbContext
using GraphQlApiFullStack.Models;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
namespace GraphQlApiFullStack.Data
{
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{
}
public DbSet<Employee> Employees { get; set; }
public DbSet<Department> Departments { get; set; }
}
}
IdentityAppDbContext.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using GraphQlApiFullStack.Models;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
namespace GraphQlApiFullStack.Data
{
public class IdentityAppDbContext : IdentityDbContext<AppUser>
{
public IdentityAppDbContext(DbContextOptions<IdentityDbContext> options) : base(options)
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
}
}
}
identityServicesExtension.cs
using System.Text;
using GraphQlApiFullStack.Data;
using GraphQlApiFullStack.Models;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
namespace GraphQlApiFullStack.Extensions
{
public static class IdentityServiceExtensions
{
public static IServiceCollection AddIdentityServices(this IServiceCollection services, IConfiguration config)
{
var builder = services.AddIdentityCore<AppUser>();
builder = new IdentityBuilder(builder.UserType, builder.Services);
builder.AddEntityFrameworkStores<IdentityAppDbContext>();
builder.AddSignInManager<SignInManager<AppUser>>();
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(config["Token:Key"])),
ValidIssuer = config["Token:Issuer"],
ValidateIssuer = true,
ValidateAudience = false
};
});
return services;
}
}
}
startup.cs
using GraphQL.Server.Ui.Voyager;
using GraphQlApiFullStack.Data;
using GraphQlApiFullStack.Extensions;
using GraphQlApiFullStack.GraphQL;
using GraphQlApiFullStack.Services;
using GraphQlApiFullStack.Services.Interfaces;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.OpenApi.Models;
namespace GraphQlApiFullStack
{
public class Startup
{
private readonly IConfiguration _configuration;
public Startup(IConfiguration configuration)
{
_configuration = configuration;
}
// 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)
{
services.AddControllers();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo {Title = "GraphQlApiFullStack", Version = "v1"});
});
// We use a pooled Db Context Factory here to avoid issues with graphql concurrency
services.AddPooledDbContextFactory<ApplicationDbContext>(builder =>
{
builder.UseSqlServer(_configuration.GetConnectionString("defaultConnection"));
});
// Identity will use just a normal db context since we wont be making multiple concurrent queries to it.
services.AddDbContext<IdentityAppDbContext>(options =>
{
options.UseSqlServer(_configuration.GetConnectionString("identityConnection"));
});
services.AddHttpContextAccessor();
services.AddGraphQLServer()
.AddQueryType<Query>()
.AddMutationType<Mutation>()
.AddFiltering()
.AddSorting()
.AddProjections();
services.AddScoped<ITokenService, TokenService>();
//services.AddIdentityServices(_configuration);
}
// 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.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "GraphQlApiFullStack v1"));
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapGraphQL();
});
app.UseGraphQLVoyager(new VoyagerOptions()
{
GraphQLEndPoint = "/graphql"
});
}
}
}

Blazor Swagger: Failed to load API definition. Fetch error: undefined /swagger/v1/swagger.json

I use .NET Core 3.1.200-preview-014977, Blazor, Swagger UI 5.0.0, my dependencies
I follow guide at https://learn.microsoft.com/en-us/aspnet/core/tutorials/getting-started-with-swashbuckle?view=aspnetcore-3.1&tabs=visual-studio . This is my config
using foo.Areas.Identity;
using foo.Controllers;
using foo.Data;
using Demo.Blazor;
using DevExpress.Blazor.DocumentMetadata;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
using System.Globalization;
using System.Net.Http;
using Microsoft.OpenApi.Models;
using System;
namespace foo
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
CultureInfo.DefaultThreadCurrentCulture = new CultureInfo("vi-VN");
services.AddServerSideBlazor().AddCircuitOptions(options => { options.DetailedErrors = true; });
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<IdentityUser>().AddRoles<IdentityRole>().AddEntityFrameworkStores<ApplicationDbContext>();
services.AddRazorPages().AddJsonOptions(options => options.JsonSerializerOptions.PropertyNamingPolicy = null);
services.AddRazorPages().AddRazorPagesOptions(options =>
{
//options.Conventions.AuthorizePage("/currencies");
//options.Conventions.AuthorizeFolder("/accounts");
});
services.AddServerSideBlazor();
services.AddScoped<AuthenticationStateProvider, RevalidatingIdentityAuthenticationStateProvider<IdentityUser>>();
services.AddSingleton<WeatherForecastService>();
services.AddDocumentMetadata((serviceProvider, registrator) =>
{
DemoConfiguration config = serviceProvider.GetService<IOptions<DemoConfiguration>>().Value;
config.RegisterPagesMetadata(registrator);
});
services.AddMvc();
services.AddHealthChecks();
services.AddHttpClient();
services.AddScoped<HttpClient>((sp) => {
var httpClient = sp.GetService<IHttpClientFactory>().CreateClient();
httpClient.DefaultRequestHeaders.Add("Accept", "application/json");
return httpClient;
});
services.AddDevExpressBlazor();
services.AddControllers();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// 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");
});
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
//app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapRazorPages();
endpoints.MapBlazorHub();
endpoints.MapFallbackToPage("/_Host");
endpoints.MapHealthChecks("/health");
});
}
}
}
I catch error:
Failed to load API definition.
How to fix it?
The issue may occur if one of your controller's is missing [Http*] attributes.
Consider the code below:
[Route("[action]")]
public async Task<IEnumerable<IdentityRole>> GetRoles()
{
_logger.LogDebug("Getting roles");
return await _roleManager.Roles.ToListAsync();
}
Your application will work, but Swagger wouldn't. Only because the example endpoint does not have [Http*] attribute defined, and thus, the swagger would fail to 'parse' your controller. Hence you see "Failed to load API definition." error message.
In this case, you would add [HttpGet] attribute like so:
[HttpGet]
[Route("[action]")]
public async Task<IEnumerable<IdentityRole>> GetRoles()
{
_logger.LogDebug("Getting roles");
return await _roleManager.Roles.ToListAsync();
}
Hope this help! This may not be an exact issue you are having, but the point is that if your controller's are not defined using common patterns, swagger will not be able to recognize them.
Good luck!
It should be like this
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("v1/swagger.json", "My API V1");
});

error downloading username by IHttpContextAccessor after publication ASP.NET

I create applications for internal use,
trying to get user login through IHttpContextAccessor
Controller:
private Microsoft.AspNetCore.Http.IHttpContextAccessor _httpContextAccessor;
var userName = _httpContextAccessor.HttpContext.User.Identity.Name;
//var userName = #"ad\LOGINUSER";
if I extract username using _httpContextAccessor.HttpContext.User.Identity.Name; mam błąd na stronie
Error.
An error occurred while processing your request.
Request ID: |77762974-42ec74070b648c99.
Development Mode
Swapping to Development environment will display more detailed information about the error that occurred.
if I use var userName = #"ad\LOGINUSER"; everything works normally
of course, the error is after publishing, everything works fine in normal compilation on computer
I'm using .net core 3.1
My startup code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using AppEcp.Models;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json.Serialization;
using Microsoft.AspNetCore.Server.IISIntegration;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.AspNetCore.Mvc.Infrastructure;
namespace AppEcp
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
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)
{
services
.AddMvc();
services
.AddHttpContextAccessor();
// services
// .TryAddSingleton<IActionContextAccessor, ActionContextAccessor>();
services
.AddAuthentication(IISDefaults.AuthenticationScheme);
services
.AddControllersWithViews()
.AddJsonOptions(options => options.JsonSerializerOptions.PropertyNamingPolicy = null);
// .AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());
services.AddCors(c =>
{
c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin());
});
var connectionAd = #"Server=wsql3;Database=ActiveDirectory;Trusted_Connection=True;MultipleActiveResultSets=true";
services.AddDbContext<UzytkownicyDbContext>(options => options.UseSqlServer(connectionAd));
var connectionUrlop = #"Server=wsql3;Database=ECP;Trusted_Connection=True;MultipleActiveResultSets=true";
services.AddDbContext<EcpDbContext>(options => options.UseSqlServer(connectionUrlop));
}
// 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("/Home/Error");
// app.UseHsts();
}
// app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Ewidencja}/{id?}");
});
}
}
}
does anyone know what i have done wrong?
You didn't enable Authentication by UseAuthentication:
app.UseAuthentication(); // add this line
app.UseAuthorization();
Within a Controller, you don't have to access HttpContext by _httpContextAccessor.HttpContext...., you can get the User by HttpContext.User.
Also, it's your duty to check whether the User is null :
var user = HttpContext.User;
if(user ==null)
{
...
}else{
var userName = user.Identity.Name;
...
}
Finally, if above changes doesn't fix the problem, could you please show us the logs?

Windows Authentication in .net Core 2.1 application

I've got a .net Core 2.1 MVC application that hosts an Angular 6 application. I am using Visual Studio 2017 15.7.3. I'm trying to set up Windows Authentication but am having issues. I've followed the documentation and my Program.cs and Startup.cs are below:
Program.cs:
using Microsoft.AspNetCore.Server.HttpSys;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Logging;
using NLog.Web;
using System;
namespace CoreIV_Admin_Core
{
public class Program
{
public static void Main(string[] args)
{
var logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
try
{
logger.Debug("init main");
CreateWebHostBuilder(args).Build().Run();
}
catch (Exception ex)
{
//NLog: catch setup errors
logger.Error(ex, "Stopped program because of exception");
throw;
}
finally
{
// Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)
NLog.LogManager.Shutdown();
}
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
//.UseHttpSys(options =>
//{
// options.Authentication.Schemes = AuthenticationSchemes.NTLM | AuthenticationSchemes.Negotiate;
// options.Authentication.AllowAnonymous = false;
//})
.ConfigureLogging(logging =>
{
logging.ClearProviders();
logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Information);
})
.UseNLog(); // NLog: setup NLog for Dependency injection
}
}
Startup.cs:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Server.HttpSys;
using Microsoft.AspNetCore.SpaServices.Webpack;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
namespace CoreIV_Admin_Core
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
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)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddAuthentication(HttpSysDefaults.AuthenticationScheme);
services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
{
HotModuleReplacement = true
});
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseHttpContext();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
routes.MapSpaFallbackRoute(
name: "spa-fallback",
defaults: new
{
controller = "Home",
action = "Index"
});
});
}
}
}
If I uncomment the .UseHttpSys section in program.cs and press play in Visual Studio to debug, it almost immediately stops the debug session and the following error is in the Event log:
"Application 'MACHINE/WEBROOT/APPHOST/myapp' with physical root
'C:\Users\me\myapp' created process with commandline 'C:\Program Files
(x86)\Microsoft Visual
Studio\2017\Professional\Common7\IDE\Extensions\Microsoft\Web
Tools\ProjectSystem\VSIISExeLauncher.exe -argFile
"C:\Users\me\AppData\Local\Temp\tmpFCA6.tmp"' but failed to listen on
the given port '28353'".
If I try with .UseHttpSys commented out, the debugging works but I am unable to be properly authenticated.
Camilo thanks for your comment, it helped point me in the right direction. I removed the UseHttpSys section from program.cs and added .UseIISIntegration(). I also changed services.AddAuthentication(HttpSysDefaults.AuthenticationScheme) to services.AddAuthentication(IISDefaults.AuthenticationScheme) in my startup.cs. I then ticked Enable Windows Authentication in the Debug section of the project properties and chose "IIS Express" for the Launch and it all worked. I'm new to .net core with windows authentication so I don't know if I got it all set up exactly correct but it works and hopefully, this post helps point others in the right direction.

.net core 3.1 identity keeps forcing user to log in after short time using Identity

I am trying to get a net core 3.1 with identity setup with Razor pages where all pages require login and I want the login to last on the browser for 300 days.
I have tried updating my startup.cs file to so that the login will last for a long time. But no matter what I have tried the login will not last more than 20 or 30 minutes. Below is my current startup.cs file.
using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using IKDataWeb.Data;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.AspNetCore.Identity.UI.Services;
using IKDataWeb.Services;
namespace IKDataWeb
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
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)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection"),
sqlServerOptions => sqlServerOptions.CommandTimeout(900)
));
services.AddDefaultIdentity<IdentityUser>(options => {
options.SignIn.RequireConfirmedAccount = true;
options.Lockout.AllowedForNewUsers = true;
})
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>();
services.ConfigureApplicationCookie(options =>
{
options.ExpireTimeSpan = TimeSpan.FromDays(300);
options.SlidingExpiration = true;
});
services.AddRazorPages().AddRazorOptions(options =>
{
options.PageViewLocationFormats.Add("/Pages/Shared/Components/Master/{0}.cshtml");
});
services.AddControllers(config =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
config.Filters.Add(new AuthorizeFilter(policy));
});
services.AddSingleton<IEmailSender, EmailSender>();
services.AddSingleton<IEmailConfiguration>(Configuration.GetSection("EmailConfiguration").Get<EmailConfiguration>());
services.AddTransient<IEmailService, EmailService>();
services.AddTransient<IFilterProducts, FilterProducts>();
}
// 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.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
});
}
}
}
Actually, it turns out that Rono was correct!
This answer did the trick.
Thanks for your help!

Categories