1
I want to check if you had any user authentication, and after checking if any user authenticated to get that user’s ID.
I have a Middleware that will redirect the user to condominium registration screen, always requiring him to register a condo if he no longer has any registered.
The problem is that Middleware is used even before a user authenticates, I need it to work only after there is authentication.
I need to change this to run only after an authentication happens.
Middleware:
public class RedirectNoCondominium
{
private readonly RequestDelegate _next;
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly string path = "~/Condominium/Add";
public RedirectNoCondominium(
RequestDelegate next,
IHttpContextAccessor httpContextAccessor)
{
_next = next;
_httpContextAccessor = httpContextAccessor;
}
public async Task Invoke(HttpContext httpContext, ICondominiumService _condominiumManager)
{
if (user != null)
{
List<ApplicationCondominium> result = await _condominiumManager.GetCondominiumAsync(user);
if (result.Count() == 0 && httpContext.Request.Path != path)
{
httpContext.Response.Redirect(path);
}
else
await _next(httpContext);
}
else
{
await _next(httpContext);
}
}
}
and call her in my startup:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseMiddleware<RedirectNoCondominium>();
app.UseForwardedHeaders();
app.Use(async (context, next) =>
{
if (context.Request.IsHttps || context.Request.Headers["X-Forwarded-Proto"] == Uri.UriSchemeHttps)
{
await next();
}
else
{
string queryString = context.Request.QueryString.HasValue ? context.Request.QueryString.Value : string.Empty;
var https = "https://" + context.Request.Host + context.Request.Path + queryString;
context.Response.Redirect(https);
}
});
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseAuthentication();
app.UseNToastNotify();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
You are using MVC?
– Joy Peter
@Joypeter I am and Identity too.
– Matheus
Possible duplicate of Error while using Middleware
– novic