2
I’m trying to use Middleware, so that every time a user logs into the system it is being redirected to condominium registration screen, he can not use the system until you register at least 1 condominium.
But I’m getting the following errors:
Code of my Middleware ~/Custom/Middleware/Redirectnocondominium.Cs
public class RedirectNoCondominium
{
private readonly UserManager<ApplicationUsers> _userManager;
private readonly ICondominiumService _condominiumManager;
private readonly RequestDelegate _next;
private readonly string path = "~/Condominium/Add";
public RedirectNoCondominium(
RequestDelegate next,
UserManager<ApplicationUsers> userManager,
ICondominiumService condominiumManager)
{
_condominiumManager = condominiumManager;
_userManager = userManager;
_next = next;
}
public ClaimsPrincipal User { get; private set; }
public async Task Invoke(HttpContext httpContext)
{
var user = await _userManager.GetUserAsync(User);
List<ApplicationCondominium> result = await _condominiumManager.GetCondominiumAsync(user.Id);
if (result.Count() == 0 && httpContext.Request.Path != path)
{
httpContext.Response.Redirect(path);
}
else
await _next(httpContext);
}
}
And here at my startup.Cs I make his call.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseMiddleware<RedirectNoCondominium>(); <-- aqui
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?}");
});
}
Matheus in my answer what were your problems found? Did you happen to use
httpContext.RequestServices.GetService(typeof(UserManager<ApplicationUsers>))
that also solves. Please do not open several questions of the same doubt we will try to solve your problem by the initial doubt that is how it does, maybe we have to change something then communicate ...– novic