# [112]天方科技 ASP.net core 教育訓練 1120406(Dto介紹、Controller補充、資料傳輸規則驗證) ## Data Transfer Object(Dto)介紹 針對傳輸設計一個Class 傳輸必要資料,過濾無須顯示的資訊 參考: [**Data Transfer Object使用心得及時機**](https://www.petekcchen.com/2010/12/how-to-use-data-transfer-object.html) ## Controller補充 ### CreatedAtAction() 發出狀態碼201,產生並且執行Action `CreatedAtAction(actionName, routeValues, value)` ```csharp! return CreatedAtAction("Gets30_student", new { id = s30_student.std_key }, s30_student); ``` ![](https://i.imgur.com/DJhQk7S.png) 參考: [**ControllerBase.CreatedAtAction 方法**](https://learn.microsoft.com/zh-tw/dotnet/api/microsoft.aspnetcore.mvc.controllerbase.createdataction?view=aspnetcore-7.0) ### DbUpdateException 資料庫在Save時,發生衝突,產生例外情況 ```csharp= try { await _context.SaveChangesAsync(); } catch (DbUpdateException) { if (s30_studentExists(s30_student.std_key))//檢查Key值是否已存在 { return Conflict();//回傳狀態碼409,衝突狀態 } else { throw;//直接丟出DbUpdateException物件,網頁的話會進入error頁面,API則會產生狀態碼500 } ``` 如果想要抓到例外情況的文字內容就要使用`InnerException` ```csharp= try { await _context.SaveChangesAsync(); } catch (DbUpdateException ex) //宣告物件變數 { if (s30_studentExists(s30_student.std_key)) { return Conflict(); } else { //if (ex.InnerException.Message != null) //由於例外情況被多層包裹,詳細例外情況須看InnerException內的訊息 // return BadRequest(ex.InnerException.Message); //else // return BadRequest(ex.Message); //可簡寫為一行 return BadRequest(ex.InnerException?.Message ?? ex.Message); //?是可能為null的表示,??是前面為null時則執行??後面的動作 //throw; } } ``` ## 資料傳輸規則驗證 **[Required]**:驗證欄位內容是否為空值或空字串。 **[EmailAddress]**:驗證欄位內容是否符合信箱格式。 **[Compare]**:比對兩個欄位內容是否相同。 **[Range]**:驗證欄位數值是否介於指定範圍中。 **[RegularExpression]**:驗證資料符合指定的規則運算式。 **[MaxLength]、[MinLength]、[StringLength]**:驗證字串長度。 **[Url]**:驗證欄位內容是否符合URL格式 。 ```csharp= public partial class s30_student { /// <summary> /// 學生基本資料 /// </summary> /// [Key] //驗證Key值 [Column(TypeName = "decimal(18, 0)")] //驗證欄位型別 public decimal std_key { get; set; } [StringLength(10)] //驗證長度 [Required] //驗證是否為空 public string std_id { get; set; } [Range(110,120, ErrorMessage ="範圍110~120之間")] //驗證範圍之間,不在範圍內,送出ErrorMessage public int? std_year { get; set; } [StringLength(45, MinimumLength = 3, ErrorMessage ="長度3-35")] //可設定最小長度,不在範圍內,送出ErrorMessage [StringLength(1, ErrorMessage ="只能一個字")] [RegularExpression(@"[MF]", ErrorMessage = "Sex must be M or F")] //正規表達式,只允許MF通過 public string std_sex { get; set; } } ``` 參考: [**將驗證新增至模型 (C#)**](https://learn.microsoft.com/zh-tw/aspnet/mvc/overview/older-versions/getting-started-with-aspnet-mvc3/cs/adding-validation-to-the-model) [**【Asp.Net Mvc】Model的驗證屬性**](http://lichunbin.blogspot.com/2014/10/aspnet-mvcmodel.html) [**正規表達式**](https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Guide/Regular_expressions) ## 反向工程 ### 當使用反向工程時,若有勾選`Use DataAnnotation attributes to configure the model`選項,會自動將資料庫的驗證設定在Model建立好,如果沒有勾選,也可以手動設定 ![](https://i.imgur.com/2U8kSDp.png) ![](https://i.imgur.com/lqL9ZOB.png)