如何在Identity包中使用MVC结构?

huangapple go评论77阅读模式
英文:

How to use MVC structure for Identity package?

问题

我在我的项目中使用了Identity包。我可以为Identity生成Razor代码,但我想要使用MVC结构。后来我找到了一个好的来源,将其添加到了我的项目中,它可以正常工作。

问题是Identity仍然使用默认的代码,而不是我从我的来源中获得的代码。比如,当我在页面上使用角色时,如果案例没有确认,它会返回到登录页面(登录页面中的代码是Identity的默认代码)。但我希望代码返回到我的代码中的"Login"操作,控制器是"Account"。

在某些情况下,我可以导航到我的MVC代码,但这不是正确的方式。Identity包如何识别我的MVC代码为自己的代码?

这是program.cs的代码:

using App;
using App.Services;
using m01_Start;
using m01_Start.Models;
using m01_Start.Services;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.AspNetCore.Mvc.Razor;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);
// 向容器添加服务。
builder.Services.AddControllersWithViews();

builder.Services.AddRazorPages();
// 添加服务
builder.Services.AddSingleton<ProductService>();
builder.Services.AddSingleton<PlanetService>();
builder.Services.AddSingleton<IdentityErrorDescriber, AppIdentityErrorDescriber>();

// 设置dbcontext
builder.Services.AddDbContext<AppDbContext>(options =>
{
     string connectionString = builder.Configuration.GetConnectionString("AppMvcConnectString");
     options.UseSqlServer(connectionString);
});

// 添加Identity
builder.Services.AddDefaultIdentity<AppUser>()
                   .AddRoles<IdentityRole>() // 添加角色错误的修复
                   .AddEntityFrameworkStores<AppDbContext>();

// 配置Identity
builder.Services.Configure<IdentityOptions>(options =>
{
     options.Password.RequireDigit = false;
     options.Password.RequireLowercase = false;
     options.Password.RequireNonAlphanumeric = false;
     options.Password.RequireUppercase = false;
     options.Password.RequiredLength = 3;
     options.Password.RequiredUniqueChars = 1;
     options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(1);
     options.Lockout.MaxFailedAccessAttempts = 3;
     options.Lockout.AllowedForNewUsers = true;
     // 用户配置
     options.User.AllowedUserNameCharacters = // 允许用户名的字符
         "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+";
     options.User.RequireUniqueEmail = true;
     options.SignIn.RequireConfirmedEmail = true;
     options.SignIn.RequireConfirmedPhoneNumber = false;
     options.SignIn.RequireConfirmedAccount = true;
});

var app = builder.Build();

if (!app.Environment.IsDevelopment())
{
     app.UseExceptionHandler("/Home/Error");
     app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.AddStatusCodePage();

app.MapAreaControllerRoute(
    name: "default",
    pattern: "{controller}/{action=Index}/{id?}",
    areaName: "ProductManage"
);

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");
app.MapRazorPages();

app.Run();

这是源代码:

https://github.com/xuanthulabnet/razorweb/blob/master/identity.mvc.zip

MVC结构的Identity代码如下:

如何在Identity包中使用MVC结构?

英文:

I use Identity package in my project. I can scaffold code Razor for Identity however I want use MVC structure. Then I found a good source and add this to my my project. It works ok.

The problem is the Identity still use the default code, not code I from my source. Such as: when I use role for the page, If the case is not confirmed, it will return to the login page (the code in the login page is the default code of Identity). But I want the code return to: action Login, controller account in my code.

I can navigate to my MVC code in some cases but that's not the way to go. How does the Identity package recognize my MVC code as its own?

This is program.cs:

using App;
using App.Services;
using m01_Start;
using m01_Start.Models;
using m01_Start.Services;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.AspNetCore.Mvc.Razor;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();

builder.Services.AddRazorPages();
// add services
builder.Services.AddSingleton&lt;ProductService&gt;();
builder.Services.AddSingleton&lt;PlanetService&gt;();
 builder.Services.AddSingleton&lt;IdentityErrorDescriber, AppIdentityErrorDescriber&gt;();


// Setup dbcontext
builder.Services.AddDbContext&lt;AppDbContext&gt;(options =&gt;
        {
             string conntectString = builder.Configuration.GetConnectionString(&quot;AppMvcConnectString&quot;);
             // System.Console.WriteLine(conntectString);
             options.UseSqlServer(conntectString);
        });

// add identity
builder.Services.AddDefaultIdentity&lt;AppUser&gt;()
                       .AddRoles&lt;IdentityRole&gt;()      // add fix add role error
                       .AddEntityFrameworkStores&lt;AppDbContext&gt;()
                    //    .AddDefaultTokenProviders()
                       ;

// Config Identity 
builder.Services.Configure&lt;IdentityOptions&gt;(options =&gt;
        {
             options.Password.RequireDigit = false; 
             options.Password.RequireLowercase = false; 
             options.Password.RequireNonAlphanumeric = false; 
             options.Password.RequireUppercase = false;
             options.Password.RequiredLength = 3;  
             options.Password.RequiredUniqueChars = 1; 
             options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(1); 
             options.Lockout.MaxFailedAccessAttempts = 3;
             options.Lockout.AllowedForNewUsers = true;
             // Cấu h&#236;nh về User.
             options.User.AllowedUserNameCharacters = // c&#225;c k&#253; tự đặt t&#234;n user
                 &quot;abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+&quot;;
             options.User.RequireUniqueEmail = true;  
             options.SignIn.RequireConfirmedEmail = true;            
             options.SignIn.RequireConfirmedPhoneNumber = false;     
             options.SignIn.RequireConfirmedAccount = true;
        });

var app = builder.Build();

if (!app.Environment.IsDevelopment())
{
     app.UseExceptionHandler(&quot;/Home/Error&quot;);
     app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.AddStatusCodePage();

app.MapAreaControllerRoute(
    name: &quot;default&quot;,
    pattern: &quot;{controller}/{action=Index}/{id?}&quot;,
    areaName: &quot;ProductManage&quot;
);

app.MapControllerRoute(
    name: &quot;default&quot;,
    pattern: &quot;{controller=Home}/{action=Index}/{id?}&quot;);
app.MapRazorPages();

app.Run();

This is source:

https://github.com/xuanthulabnet/razorweb/blob/master/identity.mvc.zip

The code MVC structure Identity:

如何在Identity包中使用MVC结构?

答案1

得分: 0

我建议使用这个项目作为参考。该应用程序旨在支持免费的.PDF,重点关注ASP.NET Core和Azure的现代Web应用程序架构。

关于您的问题,"Identity"默认移到"Identity"区域,并以"Pages"而不是MVC控制器和视图的形式实现。这在这里有示例。

这种方法可以通过命令行或包管理器控制台支持,详细信息在这里描述,并且也可以使用下面的图片中的UI。

如何在Identity包中使用MVC结构?

英文:

I recommend using this project as a reference. This application is meant to support the free .PDF focusing on the architecture of modern web applications with ASP.NET Core and Azure.

Speaking about your question, the Identity is moved to Identity area be default and implemented as Pages rather than MVC controllers and views. This is demonstrated here.

This approach is supported by both cli or Package Manager Console described here and UI like on the picture below

如何在Identity包中使用MVC结构?

答案2

得分: -1

  1. 使用dotnet new mvc命令或在Visual Studio中选择"ASP.NET Core Web Application"模板,并选择"Web Application (Model-View-Controller)"选项创建一个ASP.NET Core Web应用程序。

  2. 使用dotnet add package Microsoft.AspNetCore.Identity命令或在Visual Studio中使用NuGet包管理器将Identity包添加到您的项目中。

  3. 使用services.AddIdentity方法在Startup类的ConfigureServices方法中配置Identity服务。您可以在此方法中指定用户和角色类、密码要求、cookie设置以及其他选项。

  4. 使用app.UseAuthentication和app.UseAuthorization方法在Startup类的Configure方法中配置Identity中间件。这些方法启用MVC请求和响应的身份验证和授权功能。

  5. 创建用户注册、登录、密码重置和其他与Identity相关的操作所需的控制器、视图和模型。您可以使用内置模板或根据您的要求进行自定义。

  6. 在控制器操作或视图中使用Authorize属性或User属性来根据用户的角色或身份验证状态限制对某些区域或资源的访问。

  7. 运行应用程序并导航到登录、注册和其他页面,以测试MVC和Identity功能。您还可以在您的代码中使用Identity的API和服务来执行更高级的操作,如用户管理、基于声明的身份验证和外部身份验证提供者。

英文:

Follow this, Hope this help —

  1. Create an ASP.NET Core web application with the MVC template by using the dotnet new mvc command or selecting the "ASP.NET Core Web Application" template in Visual Studio and choosing the "Web Application (Model-View-Controller)" option.

  2. Add the Identity package to your project by using the dotnet add package Microsoft.AspNetCore.Identity command or using the NuGet Package Manager in Visual Studio.

  3. Configure the Identity services in the ConfigureServices method of the Startup class by using the services.AddIdentity method. You can specify the user and role classes, password requirements, cookie settings, and other options in this method.

  4. Configure the Identity middleware in the Configure method of the Startup class by using the app.UseAuthentication and app.UseAuthorization methods. These methods enable the authentication and authorization features for the MVC requests and responses.

  5. Create the necessary controllers, views, and models for the user registration, login, password reset, and other Identity-related actions. You can use the built-in templates or customize them according to your requirements.

  6. Use the Authorize attribute or the User property in the controller actions or views to restrict access to certain areas or resources based on the user's role or authentication status.

  7. Test the MVC and Identity features by running the application and navigating to the login, registration, and other pages. You can also use the Identity APIs and services in your code to perform more advanced operations, such as user management, claims-based authentication, and external authentication providers.

huangapple
  • 本文由 发表于 2023年5月7日 15:37:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/76192698.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定