項目改造建議:在將項目改成.net core之前,一定要先學習,不然很容易踩坑,導致項目進度變慢,.net core和asp.net mvc有很大區別
學習地址
https://docs.microsoft.com/zh-cn/aspnet/core/migration/mvc?view=aspnetcore-2.2
https://www.bilibili.com/video/av38392956/?p=8 強烈推薦
https://www.yuque.com/yuejiangliu/dotnet/solenovex-core-mvc-comp
https://www.cnblogs.com/chillsrc/p/10509412.html
https://ken.io/note/asp.net-core-tutorial-mvc-view-layout-section
項目發布到網站:
https://www.cnblogs.com/craigtaylor/p/11143484.html
https://www.cnblogs.com/humin/p/10330983.html
https://www.cnblogs.com/MrHSR/p/10374981.html#4444989 asp.net core系列 24 EF模型配置(主鍵,生成值,最大長度,並發標記)
快速開發技巧:
自動生成構造函數,在類下輸入ctor+tab鍵按兩下
方法里面參數自動生成屬性,寫完參數后,按ctrl+.,會彈出提示,然后選擇后回車即可
在非div元素處鼠標右鍵,使用<div>換行,會在元素前后加上div標簽
特別注意:.net core2.1中分組條件,必須使用new,不然單個字段分組時,不起作用,如entity.GroupBy(a => new { a.CategoryId }).Select<Xxx>
1、后台使用 HtmlEncoder.Default.Encode 防止惡意輸入(即 JavaScript)損害應用
防止重復提交常用辦法:post-redirect-get,RedirectToAction(nameOf(Detail)),使用nameOf利於重構
2、項目安裝mysql的ef支持
MySql.Data.EntityFrameworkCore、Microsoft.EntityFrameworkCore.Tools、Microsoft.EntityFrameworkCore.Proxies(延時加載)
使用Pomelo.EntityFrameworkCore.MySql替代MySql.Data.EntityFrameworkCore,因為efcore操作mysql時,出現錯誤System.InvalidOperationException:“No coercion operator is defined between types 'System.Int16' and 'System.Boolean'.”
Sql Server 請安裝 Microsoft.EntityFrameworkCore.SqlServer
3、netcore項目支持依賴注入,nuget添加Microsoft.Extensions.DependencyInjection https://stackoverflow.com/questions/32459670/resolving-instances-with-asp-net-core-di
4、efcore配置(配置 DbContext、連接字符串等)https://docs.microsoft.com/zh-cn/ef/core/miscellaneous/connection-strings
5、設置級聯刪除https://www.jianshu.com/p/39da9b023c81
6、目前針對dotnet core項目的nuget包,還不支持執行包里的代碼模板和識別Content內容,所以暫時無法實現(不能通過nuget獲取js庫或者css第三方庫,使用vs自帶libman最方便)
詳情參考 https://docs.microsoft.com/zh-cn/nuget/create-packages/project-json-impact
(6.1)、Bower 的安裝,JS包默認安裝到webroot的lib文件夾,可以通過.bowerrc文件更改安裝路徑(不推薦使用,會將很多無用的js和文件下載到項目中)
https://blog.csdn.net/qq_33303204/article/details/81323512
https://www.cnblogs.com/wanghaibin/p/9116816.html
https://www.cnblogs.com/beginfromnow/p/6883747.html
在安裝 Bower 前,請安裝它的以下依賴組件nodejs、git
安裝完成后打開 CMD 執行以下語句在全局中安裝 Bower:npm install -g bower
安裝完成后可執行以下命令驗證是否安裝成功:bower -v
在 Visual Studio 中建立 ASP.NET Core Web 應用程序。
首先你可以看到依賴項內沒有 Bower 管理,在項目右鍵也發現無管理 Bower 程序包選項。
此時我們打開 CMD。切換到項目目錄內(包含 *.csproj 的文件夾)。輸入以下命令初始化 Bower (請不要使用 PowerShell ):
bower init
在vs項目下.bowerrc文件,配置外部工具中一定要去除$(VSInstalledExternalTools)或$(VSINSTALLDIR)\Web\External勾選,不然不能下載或更新文件到wwwroot/lib中
(6.2)、使用LibMan添加依賴js和css庫,強烈推薦使用此種方法添加js和css庫
https://docs.microsoft.com/zh-cn/aspnet/core/client-side/libman/libman-vs?view=aspnetcore-2.2
https://blog.csdn.net/qq_22949043/article/details/86766808
手動還原文件
若要手動還原庫文件:
對於解決方案中的所有項目:
右鍵單擊解決方案的名稱解決方案資源管理器。
選擇還原客戶端庫選項。
對於特定的項目:
右鍵單擊libman.json中的文件解決方案資源管理器。
選擇還原客戶端庫選項。
如果添加客戶端庫時選擇提供程序為unpkg,必須輸入完下載的框架后,然后@版本號才有提示
添加jquery.validate.js等庫,搜索使用jquery-validate、jquery-validation-unobtrusive
(6.3)、配置使用npm文件安裝目錄node_modules像wwwroot目錄一樣可以使用靜態文件
在Startup.cs中加入如下代碼
app.UseStaticFiles(new StaticFileOptions
{
RequestPath = "/node_modules",
FileProvider = new PhysicalFileProvider(Path.Combine(env.ContentRootPath,"/node_modules"))
});
//使用<link href="~/node_modules/bootstrap/bootstrap.css">
7、efcore ef code first自動遷移,需要自動在數據庫中新建表
CREATE TABLE __EFMigrationsHistory ( MigrationId nvarchar(150) NOT NULL, ProductVersion nvarchar(32) NOT NULL, PRIMARY KEY (`MigrationId`) ); end;
8、ef core操作mysql 數據遷移需要導入Microsoft.EntityFrameworkCore.Design,版本是2.0.0;
https://www.cnblogs.com/whyd/p/9348325.html
https://www.cnblogs.com/Saumterer/p/7605340.html
9、ef code first一對多配置:https://blog.csdn.net/Fanbin168/article/details/81745861
10、執行數據庫遷移命令時,提示不支持PowerShell 2.0版本(don't support PowerShell version 2.0. )解決
https://www.bbsmax.com/A/6pdDBl6DJw 非常好
https://www.cnblogs.com/systemnet123/p/10262096.html
http://www.mamicode.com/info-detail-2584332.html
Add-Migration Xxxx,每次增加或修改類后,都要重新執行此命令
Update-Database -v 馬上同步本地數據庫,不適合正式環境
當執行以上命令時,如果出現錯誤Build failed,選中項目解決方案-》右鍵-》重新生成解決方案,看下項目是否有報錯的地方,當重新生成成功后,一般就可以執行了,如果還是不行,參考https://www.cnblogs.com/DHclly/p/11332591.html
11、Startup.cs取代Global.asax,Startup類負責處理所有應用程序啟動任務
BundleConfig.cs在asp.net core里面不存了,安裝Bundler & Minifier工具替代
要引用處理完的指令碼檔,在過去是使用 @Scripts.Render() 或 @Styles.Render() 將指令碼檔加入到網頁之中,現在只要在引用打包完後的指令碼檔時,加一個屬性叫 asp-append-version 的 TagHelper,把它設定為 true 就可以了。
https://dotblogs.com.tw/supershowwei/2017/07/26/164153
https://dotnetthoughts.net/bundling-and-minification-in-aspnet-core/
https://marketplace.visualstudio.com/items?itemName=MadsKristensen.BundlerMinifier
https://www.cnblogs.com/yunspider/p/9746555.html
12、Razor指令可以根據規則從 HTML 轉換為 C# 或 Razor 特定標記。 當在 @ 符號后跟 Razor 保留關鍵字時,它會轉換為 Razor 特定標記,如果不是Razor保留關鍵字,則會轉換為 C#。
@page Razor 指令將文件轉換為一個 MVC 操作,這意味着它可以處理請求。 @page 必須是頁面上的第一個 Razor 指令。 @page 是轉換成 Razor 特定標記的一個示例。
13、mvc模板頁使用:@RenderSection("header", false)
@RenderBody()
@RenderSection("Scripts", required: false)//required: false表示不是必須的
子頁面:@section header
{}
@section Scripts {
@{
await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
https://ken.io/note/asp.net-core-tutorial-mvc-view-layout-section
14、頁面文件介紹
_layout.cshtml文件中包含通用的HTML元素(腳本和樣式表)和應用程序的總體布局。例如,當你點擊RazorMvcBooks,Home,About的鏈接時,你會看到同樣的頁眉與頁腳布局。
_viewstart.cshtml文件當作_layout.cshtml文件的布局屬性來使用。可以放公用html
_viewimports.cshtml包含導入到每個Razor頁面的Razor指令。
_validationscriptspartial.cshtml文件提供對jQuery驗證腳本的引用。當我們添加創建和編輯網頁時,_validationscriptspartial.cshtml文件將被使用。
@Html.PartialAsync("_PartialViewName",data):復用View代碼,@Html.Partial()未舊方法或使用
使用<partial name="_StudentRow" for="@s">替換@Html.Partial
@await Commponent.InvokeAsync("XXX"):可復用、獨立組件、有獨立的邏輯/數據、相當於迷你mvc請求、不依賴於父級View的數據,通常放到ViewComponents文件夾下
taghelper對於寫法<vc:welcome></vc:welcome>,必須在_ViewImports.cshtml導入當前項目命名空間才能使用
15、@Html.使用TagHelper替代,Tag helpers是服務器端的C#代碼,它在Razor文件里,它會參與到創建和渲染HTML元素的過程。
asp-開頭都是taghelper,asp-action、asp-controller、asp-route-id、asp-route-name、asp-for、asp-items、asp-validation-for
_ViewImports.cshtml
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
<select asp-for="Gender" asp-items="Html.GetEnumSelectList<Gender>()"></select>
<span asp-validation-for="birthdate"></span>
<span asp-validation-summary="All"></span> 模型錯誤匯總顯示
<span asp-validation-summary="ModelOnly"></span> ModelState.AddModelError()添加的錯誤才會顯示
15.1、JavaScript TagHelpers
asp-src-include:導入指定目錄下的所有js文件,<script asp-src-include="~app/**/*.js" asp-src-exclude="~app/services/**/*.js">
asp-src-exclude:排除指定目錄下的所有js文件
asp-fallback-src:使用cdn導入js如果失敗,則使用此本地地址文件
asp-fallback-test:測試cdn的js是否引入成功
15.2、Css TagHelpers
asp-fallback-href:使用cdn導入css如果失敗,則使用此本地地址文件
asp-fallback-test-class:測試cdn文件中是否存在指定類選擇器
asp-fallback-test-property:測試cdn文件中是否存在指定屬性
asp-fallback-test-value:測試cdn文件中指定屬性是否存在指定值
15.3、asp-append-version:版本號,追加文件Hash值,通常和src一起使用
15.4、自定義元素TagHelper,新建類,類名以TagHelper結尾,繼承TagHelper,重寫Process方法
自定義TagHelper要在_ViewImport.cshtml中導入,如@addTagHelper *,Heavy.Web
使用TagHelper:<email mail-to="123@qq.com">support</email>
15.5、自定義屬性TagHelper
<bold color="green">加粗字體<bold>
<p bold color="red">加粗字體</p>
15.6、自定義類屬性TagHelper
使用自定義類TagHelper:
15.7、屬性條件TagHelper
使用條件TagHelper
15.8、TagHelper前綴,可以頁面中指定前綴的元素,TagHelper才生效
@tagHelperPrefix "my:"
16、獲取控制器和action名稱
this.ControllerContext.ActionDescriptor.ControllerName
this.ControllerContext.ActionDescriptor.ActionName
17、.net core Identity用戶登錄使用
核心對象UserManager<IdentityUser>、SignInManager<IdentityUser>、RoleManager<IdentityRole>
使用在Startup.cs中配置
string connectionString = Configuration.GetConnectionString("MysqlConnection");
//注冊數據庫上下文
services.AddDbContext<Data.NBSharpDbContext>(options => options.UseMySql(connectionString));
//注冊Identity
services.AddDbContext<IdentityDbContext>(options => options.UseMySql(connectionString));
services.AddIdentity<IdentityUser, IdentityRole>(options =>
{
options.Password.RequireNonAlphanumeric = false;
options.Password.RequireLowercase = false;
options.Password.RequireUppercase = false;
options.Password.RequiredLength = 1;
}).AddEntityFrameworkStores<IdentityDbContext>();
app.UseAuthentication();//全局身份認證,必須放在app.UseMvc()之前
執行數據庫遷移Add-migration InitIdentity -Context IdentityDbContext
//頁面中判斷是否登錄@if(SignInManager.IsSignedIn(User)){...}
//Controller用戶登錄才能訪問,再Controller或Action上加上[Authorize]即可
18、頁面中使用注入對象@inject SignInManager<IdentityUser> SignInManager
SignInManager為變量名
19、mvp提供增刪改查參考https://github.com/solenovex/ASP.NET-Core-MVC-Tutorial-Code
RoleController AddUserToRole()中代碼應該調整為
// 使用SQL語句的方式實現
// 方法一、推薦,先查所有用戶,再查角色的用戶,然后在內存中排除
// 所有用戶
var users = await _userManager.Users*************);
// 當前角色包含的用戶
var users2 = await _userManager.Users.FromSql(
"select u.* from AspNetUsers u, AspNetUserRoles r where u.Id = r.UserId and r.RoleId = @roleId ",
new SqlParameter("@roleId", roleId))*************);
// 添加當前角色不包含的用戶
vm.Users.AddRange(users.Where(u => users2.Contains(u) == false));
// 方法二、不推薦,直接使用 not in語句
//vm.Users.AddRange(await _userManager.Users.FromSql(
// "select u.* from AspNetUsers u where u.Id not in (select UserId from AspNetUserRoles where RoleId = {0})",
// roleId)*************));
20、.net-core的api接口不再返回HttpResponseMessage,返回和mvc控制層一樣、可以是JsonResult、void、string等待
21、.net-core里面使用HttpContext對象
public class xxxAppService : PlatformAppService { private readonly IHttpContextAccessor httpContextAccessor; public xxxAppService(IHttpContextAccessor _httpContextAccessor) { httpContextAccessor = _httpContextAccessor; } public async Task<string> GetHeaders() { var headers = httpContextAccessor.HttpContext.Request.Headers; return headers["Authorization"]; } }
22、.netcore中使用HttpContext對象 https://docs.microsoft.com/en-us/aspnet/core/fundamentals/http-context?view=aspnetcore-2.2
23、.netcore執行sql查詢 語句https://docs.microsoft.com/zh-cn/ef/core/querying/raw-sql
默認生成的為Person的Model,如果Select獲取的字段中不包含Person中的某字段就會拋異常了,例如:下面的語句只獲取name字段,並沒有包含Person的其他字段,那么拋異常:The required column 'id' was not present in the results of a 'FromSql' operation.
db.Set<Person>().FromSql($"select name from {nameof(Person)} ").ToList(); 那么改為: db.Set<Person>().Select(l => l.name).FromSql($"select name from {nameof(Person)} ").ToList();
24、View Component
顯示部分內容、Mini Controller、可復用、只能配合父級View使用
實現ViewComponent
使用ViewComponent,新建文件夾:Components/InternetStatus/Default.cshtml(可放到Shared文件夾下,全局通用)
具體頁面中使用此ViewComponent@await Component.InvokeAsync("InternetStatus")
25、診斷中間件UseDeveloperExceptionPage、UseStatusCodePages、UseExceptionHandler、UseWelcomePage
.net core項目重命名后錯誤解決:
錯誤 NETSDK1007 找不到“E:\Project\MyProject\MyProject.Common\MyProject.Utility.csproj”的項目信息。這可以指示缺少一個項目引用。 MyProject.Data C:\Program Files\dotnet\sdk\2.2.107\Sdks\Microsoft.NET.Sdk\targets\Microsof