error downloading username by IHttpContextAccessor after publication ASP.NET - c#

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?

Related

"Configuration config = new Configuration": 'Configuration' is a namespace but is used like a type

very new to .net and this seems like a simple questions.
Trying to get this code to work from the Jaeger website: https://ocelot.readthedocs.io/en/latest/features/tracing.html
services.AddSingleton<ITracer>(sp =>
{
var loggerFactory = sp.GetService<ILoggerFactory>();
Configuration config = new Configuration(context.HostingEnvironment.ApplicationName, loggerFactory);
var tracer = config.GetTracer();
GlobalTracer.Register(tracer);
return tracer;
});
services
.AddOcelot()
.AddOpenTracing();
in the startup.cs file under the ConfigureServices. I have added the proper references, but am getting an error with the:
Configuration config = new Configuration(context.HostingEnvironment.ApplicationName, loggerFactory);
Visual studio keeps complaining:
'Configuration' is a namespace but is used like a type
Any ideas on how to fix.
Here is what I have in startup so far:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Configuration;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Ocelot;
using Ocelot.DependencyInjection;
using Ocelot.Middleware;
using Ocelot.Provider.Consul;
using Microsoft.Identity.Web;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Identity.Web.TokenCacheProviders.InMemory;
using System.Text;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using Ocelot.Logging;
using OpenTracing.Noop;
using OpenTracing.Propagation;
using OpenTracing.Util;
using Ocelot.Tracing.OpenTracing;
namespace Ocelot.Demo1
{
public class Startup
{
public Startup(IConfiguration configuration)
{
_Configuration = configuration;
}
public ILoggerFactory _loggerFactory;
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.AddCors(options =>
{
options.AddDefaultPolicy(
builder =>
{
// builder.WithOrigins("http://localhost:5200");
builder.WithOrigins("http://localhost:5200")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
});
});
// Azure AD
services.Configure<JwtBearerOptions>(JwtBearerDefaults.AuthenticationScheme, jwtOptions => {
jwtOptions.Audience = "RANDOM TOKEN VALUE";
jwtOptions.Authority = "https://login.microsoftonline.com/YOUR_MS_DOMIAN/";
jwtOptions.RequireHttpsMetadata = false;
jwtOptions.Events = new JwtBearerEvents { OnAuthenticationFailed = AuthenticationFailed, OnTokenValidated = AuthenticationTokenValidated };
jwtOptions.TokenValidationParameters.ValidIssuer = "https://login.microsoftonline.com/RANDOM TOKEN VALUE/v2.0";
});
services.Configure<JwtBearerOptions>(JwtBearerDefaults.AuthenticationScheme, jwtOptions => {
jwtOptions.Events = new JwtBearerEvents { OnAuthenticationFailed = AuthenticationFailed, OnTokenValidated = AuthenticationTokenValidated };
});
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer();
//.AddMicrosoftIdentityWebApi(Configuration,"AzureAD");
// services.AddProtectedWebApi(Configuration).AddProtectedApiCallsWebApis(Configuration).AddInMemoryTokenCaches();
services.AddSingleton<ITracer>(sp =>
{
var loggerFactory = sp.GetService<ILoggerFactory>();
Configuration config = new Configuration("Ocelot API Gateway", loggerFactory);
var tracer = config.GetTracer();
GlobalTracer.Register(tracer);
return tracer;
});
// Call Ocelot
services.AddOcelot(_Configuration)
.AddOpenTracing();
services.AddControllers();
}
// 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.UseHttpsRedirection();
app.UseRouting();
app.UseCors();
app.UseAuthorization();
app.UseAuthentication();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
app.UseOcelot().Wait();
}
private Task AuthenticationFailed(AuthenticationFailedContext arg)
{
// For debugging purposes only!
var s = $"AuthenticationFailed: {arg.Exception.Message}";
arg.Response.ContentLength = s.Length;
//arg.Response.Body.Write(System.Text.Encoding.UTF8.GetBytes(s), 0, s.Length);
return Task.FromResult(0);
}
private Task AuthenticationTokenValidated(TokenValidatedContext arg)
{
// For debugging purposes only!
var s = $"AuthenticationTokenValidated: {arg.Result}";
return Task.FromResult(0);
}
}
}
you are using System.Configuration namespace which causes ambiguity.
i would suggest remove the using System.Configuration. And try specifying fully qualified name for the Configuration. visual studio would suggest possible candidates (press Ctrl . on the Class name you want to qualify) provided you have added all required references in project already.
If you have a
using System;
then the C# compiler gets confused with Configuration and thinks it refers to the namespace System.Configuration. You can solve it by using the explicit namespace Jaeger:
var config = new Jaeger.Configuration(
context.HostingEnvironment.ApplicationName, loggerFactory);

Getting SameSite cookie issues with Azure AD authentication with downstream WebAPI

I added support in my Blazor Server app for downstream API in which I send an access token to the API. This caused the authentication against Azure AD to stop working, by giving me cookies that chrome refuses due to SameSite policy (it does authenticate, but can't save the cookie). It works fine from localhost, but not at all in Azure. The warning I get in Chrome is:
A cookie associated with a cross-site resource at https://---snip---.azurewebsites.net/ was set without the SameSite attribute. It has been blocked, as Chrome now only delivers cookies with cross-site requests if they are set with SameSite=None and Secure. You can review cookies in developer tools under Application>Storage>Cookies and see more details at https://www.chromestatus.com/feature/5088147346030592 and https://www.chromestatus.com/feature/5633521622188032.
(from uri: https://login.microsoftonline.com/98f2d82c-c037-4c5f-a381-074c1428381c/reprocess?ctx=...)
The only code I can think of that would give me this issue is the following, which retrieves the access token, and handles the exception in Blazor. This code is from here:
https://github.com/AzureAD/microsoft-identity-web/wiki/Managing-incremental-consent-and-conditional-access
private async Task<string> GetAccessToken(string[] requiredScopes)
{
string[] scopes = requiredScopes ?? _configuration["DownstreamAPI:Scopes"]?.Split(' ');
string accessToken = null;
try
{
accessToken = await _tokenAcquisition.GetAccessTokenForUserAsync(scopes);
}
catch (Exception ex)
{
_consentHandler.HandleException(ex);
}
return accessToken;
}
My Startup.cs:
using Blazored.Modal;
using Airline.CAM.WebUI.Utility;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Identity.Web;
using Microsoft.Identity.Web.UI;
using System.Net.Http;
using Microsoft.AspNetCore.Http;
namespace Airline.CAM.WebUI
{
public class Startup
{
public Startup(IConfiguration configuration, IWebHostEnvironment webHostEnvironment)
{
Configuration = configuration;
WebHostEnvironment = webHostEnvironment;
}
public IConfiguration Configuration { get; }
public IWebHostEnvironment WebHostEnvironment { get; set; }
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.Unspecified;
options.HandleSameSiteCookieCompatibility();
});
services.Configure<OpenIdConnectOptions>(OpenIdConnectDefaults.AuthenticationScheme, options =>
{
options.TokenValidationParameters.RoleClaimType = "roles";
options.NonceCookie.SameSite = SameSiteMode.None;
});
var scopes = new[] { "api://---snip---/Cam_access_as_user" };
services.AddMicrosoftIdentityWebAppAuthentication(Configuration, "AzureAd")
.EnableTokenAcquisitionToCallDownstreamApi(scopes)
.AddInMemoryTokenCaches();
services.AddMicrosoftGraph(scopes, "https://graph.microsoft.com/v1.0");
if (!WebHostEnvironment.IsDevelopment())
{
services.AddSignalR().AddAzureSignalR(options =>
{
options.ServerStickyMode = Microsoft.Azure.SignalR.ServerStickyMode.Required;
});
}
services.AddControllersWithViews(options =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
options.Filters.Add(new AuthorizeFilter(policy));
}).AddMicrosoftIdentityUI();
services.AddScoped<JsConsole>();
services.AddScoped<HttpClient>();
services.AddScoped<Utility.DownstreamWebApi>();
services.AddScoped<ApiHelper>();
services.AddRazorPages();
services.AddServerSideBlazor(o => o.DetailedErrors = true).AddMicrosoftIdentityConsentHandler();
services.AddBlazoredModal();
services.AddApplicationInsightsTelemetry(Configuration["APPINSIGHTS_INSTRUMENTATIONKEY"]);
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseExceptionHandler("/Error");
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapBlazorHub();
endpoints.MapFallbackToPage("/_Host");
});
}
}
}

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

Ambiguity between 'Startup.Configuration' and 'Startup.Configuration'

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.

.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