首先請using這個類庫。
using Microsoft.AspNetCore.Identity;
這個類庫老牛逼了,首先是包含了一個IdentityUser類。我們可以自己寫一個User類繼承IdentityUser,這樣一來,很多屬性我就不用手動建了。如你所見,我的User沒有Emai這個字段,但是IdentityUser有這個字段。
public class User:IdentityUser { public string Pass { get; set; } public string DisplayName { get; set; } public DateTime RegisteredTime { get; set; } }
如何把用戶發來的數據變成一個User並且存入數據庫?
顯然,我他媽得先創建並且連接一個數據庫。
創建數據庫如果使用VSStudio是賊容易的一件事,只需要打開'視圖菜單',然后點開'SQL Server對象資源管理器'。然后你就看到下面這個圖。在上面點右鍵然后添加一個SQL服務器,然后在服務器上點右鍵查看屬性,可以得到鏈接字符串。
這種簡單的操作顯然難不住你。下一步把連接字符串放到appsetting.json里面,下面這是一種推薦做法。你當然可以直接粘貼到你的startUp.cs文件中。不過誰會這么做呢?
"ConnectionStrings": { "DefaultConnection": "這里就是你的連接字符串" }
下一步要用這個連接字符串連上你的數據庫。注意帶顏色的字。很JB重要。
// 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; }); // 看到了么,下面這行代碼用來連接數據庫。這是EF提供的方法。 services.AddDbContext<AppContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); // 在這里指定你的User類,然后再指定你的數據庫。這是Identity類庫提供的方法。 services.AddDefaultIdentity<User>().AddEntityFrameworkStores<AppContext>(); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); }
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseCookiePolicy(); // 這里必須用上。 app.UseAuthentication(); app.UseMvc(); }
經過上面的配置,controller里面就可以注入很多方法。這下你看起來牛逼多了。
數據庫連上了,接下來是真槍實彈的創建一個用戶,是時候寫controller了。
建一個隨便什么controller吧。我建的是UserController,你可以隨你的便。關我屌事呢?
在controller的構造函數里面注入一個UserManager的類,這個類也是Identity提供的。
public class UserController : ControllerBase { private readonly UserManager<User> _userManager; public UserController(UserManager<User> userManager) { _userManager = userManager; } ......
這個UserManager有賊多的方法,這里我只用一個,createAsync方法。
// POST: api/User [HttpPost] public async Task PostAsync([FromBody]User _user) { //先創建一個user,不包括密碼
var user = new User { Email = _user.Email , UserName = _user.UserName};
//將user和密碼綁定入庫 var result = await _userManager.CreateAsync(user, _user.Pass); if (result.Succeeded) { Console.Write("注冊成功!"); } }
用Postman模擬一個請求。你注意到那個FromBody了嗎?這個標記可以把發過來的json請求解析成User格式。
這里有一個新手大坑。如果你的 [FromBody] User _user這里寫的是[FromBody] string _user, 你就不能用json格式發。會報什么json解析錯誤。
發送請求以后去看看你的數據庫吧。已經創建好了一個User對象並且存到了你的數據庫里。
這么多字段都是來自IdentityUser類,其中只有那個pass字段是我自己UserClass里面的。
最后補充【關於Migration】:
如果你報500錯誤,說什么表名無效的話。你需要做一下Migration。說白了就是:讓數據庫的表結構和你代碼的Model結構相同。比如你現在有了一個UserModel,可是數據庫沒有User這個表。那么你能創建成功才他媽有鬼了。
怎么Migration?
簡單。
這是創建一個名為“InitialCreate”的Migration 如果你用的是powershell Add-Migration InitialCreate 如果你用的是console dotnet ef migrations add InitialCreate 然后更新數據庫 >powershell Update-Database >console dotnet ef database update