IdentityBuilder does not contain a definition for 'AddEntityFrameworkStores - c#

I am using .netcore 3.1. While using the following 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.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
///using AspNetCore3JWT.Data;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using Jwt.Data;
namespace Jwt
{
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.AddControllers()
.AddNewtonsoftJson();
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
}
// 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.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
I got this error:

I just upgraded a project to .net core 3.1, and had to change the following line from
services.AddDefaultIdentity<ApplicationUser>().AddEntityFrameworkStores<DBContext>();
To
services.AddDefaultIdentity<ApplicationUser>().AddUserStore<DBContext>();

In addition to installing the package Microsoft.AspNetCore.Identity.EntityFrameworkCore per serpent5's comment, I also had to install the package Microsoft.AspNetCore.Identity.UI.

Make sure you inherit from IdentityDbContext not DbContext only

Related

An unhandled exception occurred while processing the request. Identity View Models

I'm trying to display a name that's stored in a database when you go to user's profile. However i get this error
InvalidOperationException: Unable to resolve service for type
'Website_friend_feature.Areas.Identity.Data.ApplicationUser' while
attempting to activate
'Website_friend_feature.Controllers.UserController'.
I searched it and i did find an answer on here but it didn't work for me. here
When i implement the solution it says this schema already appears in program.cs. So i dont think that solution is for me. What am I doing wrong? Is it the way i'm calling the model in the view?
controller:
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Website_friend_feature.Areas.Identity.Data;
namespace Website_friend_feature.Controllers
{
public class UserController : Controller
{
private readonly ApplicationUser _AU;
private readonly UserManager<ApplicationUser> _userManager;
public UserController (ApplicationUser AU, UserManager<ApplicationUser> userManager)
{
_AU = AU;
_userManager = userManager;
}
//...
}
}
startup.cs:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Website_friend_feature.Areas.Identity.Data;
using Website_friend_feature.Data;
namespace Website_friend_feature
{
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.AddControllersWithViews();
services.AddRazorPages();
services.AddDbContext<AuthDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("AuthDbContextConnection")));
}
// 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();
}
else
{
app.UseExceptionHandler("/Home/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.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapRazorPages();
});
}
}
}

Cors policy error when using Authorize Attribute

I am getting a cors policy error whenever I use Authorize attribute on my user controller.I am using Angular 8 as my front-end framework and asp .net core 3.0.0 as my backend.It is working fine if I remove the authorize attribute from the controller.
.
Below is my startup.cs file.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using AutoMapper;
using DatingApp.API.Data;
using DatingApp.API.Helpers;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace DatingApp.API {
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_3_0);
services.AddDbContext<DataContext>(x => x.UseSqlite(Configuration.GetConnectionString("DefaultConnection")));
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
});
services.AddAutoMapper(typeof(DatingRepository).Assembly);
services.AddScoped<IAuthRepository, AuthRepository>();
services.AddScoped<IDatingRepository, DatingRepository>();
}
// 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();
}
else
{
app.UseExceptionHandler(builder =>
{
builder.Run(async context =>
{
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
var error = context.Features.Get<IExceptionHandlerFeature>();
if (error != null)
{
context.Response.AddApplicationError(error.Error.Message);
await context.Response.WriteAsync(error.Error.Message);
}
});
});
// 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.UseRouting();
app.UseAuthorization();
app.UseCors("CorsPolicy");
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers().RequireCors("CorsPolicy");
});
}
}
}
This is my usercontroller
Firstly I need to add app.UseAuthentication(); for adding the authentication as a middleware in my startup.cs file and then I also need to configure the same in my services.
Here is modification in startup.cs file
If anyone faces a similar issue and has their Authentication already setup correctly in startup.cs file.
Remember folks below is the right hierarchy:
app.UseRouting();
app.UseCors("AllowAnyOrigin");
app.UseAuthentication();
app.UseAuthorization();
I was using app.UseCors() below authentication which was causing the issue.

Entity Framework .Net Core using VS2019 Community on Mac OS don't works

I try to use EF core 3.1.0, could you see above:
enter image description here
I created a DBContext class:
using System;
using Microsoft.EntityFrameworkCore;
using SGC.ApplicationCore.Entity;
namespace SGC.Infrastructure.Data
{
public class ClienteContext:DbContext
{
public ClienteContext(DbContextOptions<ClienteContext> options):base(options)
{ }
public DbSet<Cliente> Clientes { get; set; }
public DbSet<Contato> Contatos { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Cliente>().ToTable("Cliente");
modelBuilder.Entity<Contato>().ToTable("Contato");
}
}
And I inserted this code in UI project Startup.cs:
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.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using SGC.Infrastructure.Data;
namespace SGC.UI.Web
{
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.AddControllersWithViews();
services.AddDbContext<ClienteContext>(c => c.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, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/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.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
And the code of Program.cs class is:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace SGC.UI.Web
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
When I try to run de Migrations command, it throw this exception:
Unable to create an object of type 'ClienteContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728
If I change the constructor of ClienteContext.cs to a parameterless constructor the migrations command works.
migration commands:
dotnet ef migrations add Inicial

After migrating my app to ASP.NET Core 3.0, the previously valid Index URL returns 404

An app started in ASP.NET Core 2.0 (I think), then migrated to 2.1, then to 2.2, now I'm trying and failing to migrate it to 3.0...
I read and tried to apply instructions in the official migration docs, according to which I was supposed to (among others) replace services.AddMvc() with services.AddRazorPages() and app.UseMvc() with app.UseEndpoints(endpoints => {endpoints.MapRazorPages();}) if I was using Razor Pages. Since as far as I'm aware I was always using Razor Pages and never full-blown MVC, this is what I did.
Now previously working URLs return HTTP 404 instead of any content...
For instance, the / or /Index route does this, even though in the project directory there is a Pages/Index.cshtml file as well as a Pages/Index.cshtml.cs file. (Although oddly: maybe it is only the Index url that is failing - I just tried pointing my browser to /Error and it worked!)
Pages/Index.cshtml.cs content (unchanged from the working version):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Mon.Battle;
namespace mon.Pages
{
public class IndexModel : PageModel
{
public IndexModel(IBattleManager battleManager)
{
// I hope I don't have to lock this dict here, I'm only reading
configurationSerialized = battleManager.configurationSerialized;
}
public ConfigurationSerializedFormat configurationSerialized;
public void OnGet()
{
}
}
}
Pages/Index.cshtml also contains some content, but it is too long and too messy to post it here as a whole... But it should definitely return something and it was returning something before migrating to 3.0.
Page directives from the top of Index.cshtml are short enough however:
#* TODO: The site becomes ugly :( Should I start using Bootstrap, instead of trying to handcraft CSS? *#
#* Hey... I actually start to like how the site looks :) *#
#page
#using System.Text.Encodings.Web
#using Microsoft.Extensions.Configuration
#inject JavaScriptEncoder jsencoder
#inject IConfiguration conf
#using static System.Text.Json.JsonSerializer
#model IndexModel
#{
Layout = null;
}
These, unfortunately, had to change a bit from the pre-migration version: namely since 3.0 removed Newtonsoft.JSON, I had to replace it with System.Text.Json.
My current Startup.cs (I thought I applied instructions from the aforementioned docs precisely):
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.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.EntityFrameworkCore;
using mon.Data;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Mon.Chat;
using Mon.MatchMaker;
using Mon.Battle;
using Mon.Player;
namespace mon
{
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.Configure<IdentityOptions>(options =>
{
options.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
});
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<ApplicationUser>().AddRoles<IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddRazorPages();
services.AddSignalR();
services.AddSingleton<IBattleManager, BattleManager>();
}
// 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");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseEndpoints(endpoints =>
{
endpoints.MapHub<ChatHub>("/chathub");
endpoints.MapHub<MatchMakerHub>("/mmrhub");
endpoints.MapHub<BattleHub>("/battlehub");
endpoints.MapRazorPages();
});
}
}
}
Previous Startup.cs:
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.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using mon.Data;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Mon.Chat;
using Mon.MatchMaker;
using Mon.Battle;
using Newtonsoft.Json.Serialization;
using Mon.Player;
namespace mon
{
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.Configure<IdentityOptions>(options =>
{
options.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
});
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<ApplicationUser>().AddRoles<IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services
.AddSignalR()
.AddJsonProtocol(options =>
{
options.PayloadSerializerSettings.ContractResolver = new DefaultContractResolver();
});
services.AddSingleton<IBattleManager, BattleManager>();
}
// 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.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseAuthentication();
app.UseSignalR(routes =>
{
routes.MapHub<ChatHub>("/chathub");
routes.MapHub<MatchMakerHub>("/mmrhub");
routes.MapHub<BattleHub>("/battlehub");
});
app.UseMvc();
}
}
}
What am I doing wrong? What did I miss? Why does /Index return HTTP 404?
If you ask for any more info I'll provide.
Once I had the issue with my .csproj file. Make sure your file(s) are not listed like:
<ItemGroup>
<Content Remove="Views\Extractor\Insert.cshtml" />
<Content Remove="Views\_ViewImports.cshtml" />
</ItemGroup>
This might happen when we copy paste the file/ change the build action etc.

How can I protect an asp.net core middleware with cookies?

I would develop an ASP.NET Core web API that redirects received HTTP API after cookie authentication.
Below my Startup.cs file:
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using MyProject.Middlewares;
namespace MyProject.Backend
{
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.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie();
services.AddTransient(typeof(ReverseProxyMiddleware));
}
// 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.UseHsts();
}
app.UseCookiePolicy();
app.UseAuthentication();
app.UseHttpsRedirection();
app.UseReverseProxyMiddleware();
}
}
}
And below my middleware:
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using System;
using System.Threading.Tasks;
namespace MyProject.Middlewares
{
public class ReverseProxyMiddleware : IMiddleware
{
[Authorize]
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
// HTTP redirection...
}
}
}
Actually, if I try to perform an HTTP request without cookie I obtain 200 results. How can I protect my middleware?
Thanks

Categories