<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          .NET 云原生架構(gòu)師訓(xùn)練營(模塊二 基礎(chǔ)鞏固 MVC終結(jié)點(diǎn))--學(xué)習(xí)筆記

          共 6694字,需瀏覽 14分鐘

           ·

          2020-12-28 00:36

          2.3.4 Web API -- MVC終結(jié)點(diǎn)

          • MVC與MVVM

          • 模型綁定

          • 自定義模型綁定器

          • 模型驗(yàn)證

          • 返回?cái)?shù)據(jù)處理

          MVC與MVVM

          MVC

          ASP.NET Core MVC 概述:https://docs.microsoft.com/zh-cn/aspnet/core/mvc/overview?view=aspnetcore-5.0

          MVVM

          ASP.NET Core 中的 Razor Pages 介紹:https://docs.microsoft.com/zh-cn/aspnet/core/razor-pages/?view=aspnetcore-5.0&tabs=visual-studio

          Razor Pages 沒有 Controller,Model 中可以包含方法

          ASP.NET Core MVC 注入

          services.AddControllers();

          app.UseEndpoints(endpoints =>
          {
          endpoints.MapControllers();
          });

          MVC Endpoint

          模型綁定

          • 什么是模型綁定

          • 來源有哪些

          • 復(fù)雜的數(shù)據(jù)綁定

          ASP.NET Core 中的模型綁定:https://docs.microsoft.com/zh-cn/aspnet/core/mvc/models/model-binding?view=aspnetcore-5.0

          什么是模型綁定

          控制器和 Razor 頁面處理來自 HTTP 請(qǐng)求的數(shù)據(jù)。例如,路由數(shù)據(jù)可以提供一個(gè)記錄鍵,而發(fā)布的表單域可以為模型的屬性提供一個(gè)值。編寫代碼以檢索這些值,并將其從字符串轉(zhuǎn)換為 .NET 類型不僅繁瑣,而且還容易出錯(cuò)。

          模型綁定會(huì)自動(dòng)化該過程。模型綁定系統(tǒng):

          • 從各種源(如路由數(shù)據(jù)、表單域和查詢字符串)中檢索數(shù)據(jù)。

          • Razor在方法參數(shù)和公共屬性中向控制器和頁面提供數(shù)據(jù)。

          • 將字符串?dāng)?shù)據(jù)轉(zhuǎn)換為 .NET 類型。

          • 更新復(fù)雜類型的屬性。

          來源有哪些

          • [FromQuery] -從查詢字符串獲取值。

          • [FromRoute] -從路由數(shù)據(jù)中獲取值。

          • [FromForm] -從已發(fā)布的表單字段中獲取值。

          • [FromBody] -從請(qǐng)求正文中獲取值。

          • [FromHeader] -從 HTTP 標(biāo)頭中獲取值。

          從路由數(shù)據(jù)中獲取值

          [HttpGet]
          [Route("option/{id}")]
          public IActionResult GetOption([FromRoute] int id)
          {
          return Ok(new {id});
          }

          從查詢字符串獲取值

          [HttpGet]
          [Route("option/{id}")]
          public IActionResult GetOption([FromRoute] int id, [FromQuery] string name)
          {
          return Ok(new {id, name});
          }

          從 HTTP 標(biāo)頭中獲取值

          [HttpGet]
          [Route("option/{id}")]
          public IActionResult GetOption([FromRoute] int id, [FromQuery] string name,[FromHeader] string termId)
          {
          return Ok(new {id, name, termId});
          }

          從已發(fā)布的表單字段中獲取值

          [HttpPost]
          [Route("option/from")]
          public IActionResult CreateOption([FromForm] string name, [FromForm] string id)
          {
          return Ok(new {name, id});
          }

          從請(qǐng)求正文中獲取值

          [HttpPost]
          [Route("option/body")]
          public IActionResult CreateOption([FromBody] string name)
          {
          return Ok(name);
          }

          復(fù)雜的數(shù)據(jù)綁定

          • 對(duì)象

          • 集合

          • 字典

          對(duì)象

          public class Student
          {
          public int Id { get; set; }

          public string Name { get; set; }
          }

          [HttpPost]
          [Route("option/body")]
          public IActionResult CreateOption([FromBody] Student student)
          {
          return Ok(student);
          }

          字典

          [HttpGet]
          [Route("option")]
          public IActionResult GetOption([FromQuery] Dictionary<int, string> dic)
          {
          var students = new List();

          foreach (var item in dic)
          {
          students.Add(new Student {Id = item.Key, Name = item.Value});
          }

          return Ok(students);
          }

          啟動(dòng)程序,訪問:https://localhost:5001/config/option?dic[1001]=ming$dic[1002]=rank&dic[1003]=abc

          輸出:

          [{"id":1001,"name":"ming$dic[1002]=rank"},{"id":1003,"name":"abc"}]

          自定義模型綁定器

          ASP.NET Core 中的自定義模型綁定:https://docs.microsoft.com/zh-cn/aspnet/core/mvc/advanced/custom-model-binding?view=aspnetcore-5.0

          ModelBinder

          [ModelBinder(BinderType = typeof(AuthorEntityBinder))]
          public class Author
          {
          public int Id { get; set; }
          public string Name { get; set; }
          public string GitHub { get; set; }
          public string Twitter { get; set; }
          public string BlogUrl { get; set; }
          }

          public class AuthorEntityBinder : IModelBinder

          ModelBinderProvider

          public class AuthorEntityBinderProvider : IModelBinderProvider

          services.AddControllers(options =>
          {
          options.ModelBinderProviders.Insert(0, new AuthorEntityBinderProvider());
          });

          模型驗(yàn)證

          • 什么是模型驗(yàn)證

          • 模型驗(yàn)證的特性與消息

          • FluentValidation

          什么是模型驗(yàn)證

          ASP.NET Core MVC 和頁面中的模型驗(yàn)證 Razor:https://docs.microsoft.com/zh-cn/aspnet/core/mvc/models/validation?view=aspnetcore-5.0

          Web 應(yīng)用負(fù)責(zé)檢查 ModelState.IsValid 并做出相應(yīng)響應(yīng)

          if (!ModelState.IsValid)
          {
          return Page();
          }

          模型驗(yàn)證的特性與消息

          • [CreditCard]:驗(yàn)證屬性是否具有信用卡格式。

          • [Compare]:驗(yàn)證模型中的兩個(gè)屬性是否匹配。

          • [EmailAddress]:驗(yàn)證屬性是否具有電子郵件格式。

          • [Phone]:驗(yàn)證屬性是否具有電話號(hào)碼格式。

          • [Range]:驗(yàn)證屬性值是否在指定的范圍內(nèi)。

          • [RegularExpression]:驗(yàn)證屬性值是否與指定的正則表達(dá)式匹配。

          • [Required]:驗(yàn)證字段是否不為 null。

          • [StringLength]:驗(yàn)證字符串屬性值是否不超過指定長度限制。

          • [Url]:驗(yàn)證屬性是否具有 URL 格式。

          • [Remote]:通過在服務(wù)器上調(diào)用操作方法來驗(yàn)證客戶端上的輸入。

          [Required] [Range]

          public class Student
          {
          [Required]
          [Range(1,10,ErrorMessage = "id 為 1-10 之間的數(shù)字")]
          public int Id { get; set; }

          public string Name { get; set; }
          }

          ModelState

          [HttpPost]
          [Route("option/body")]
          public IActionResult CreateOption([FromBody] Student student)
          {
          if (!ModelState.IsValid)
          {
          return ValidationProblem();
          }

          return Ok(student);
          }

          FluentValidation

          不同場(chǎng)景下同一個(gè)模型有不同的驗(yàn)證規(guī)則,最好將模型與驗(yàn)證分開

          表達(dá)式寫法:

          public class CustomerValidator : AbstractValidator<Customer> {
          public CustomerValidator() {
          RuleFor(x => x.Surname).NotEmpty();
          RuleFor(x => x.Forename).NotEmpty().WithMessage("Please specify a first name");
          RuleFor(x => x.Discount).NotEqual(0).When(x => x.HasDiscount);
          RuleFor(x => x.Address).Length(20, 250);
          RuleFor(x => x.Postcode).Must(BeAValidPostcode).WithMessage("Please specify a valid postcode");
          }

          private bool BeAValidPostcode(string postcode) {
          // custom postcode validating logic goes here
          }
          }

          Installation:https://docs.fluentvalidation.net/en/latest/installation.html

          Install-Package FluentValidation

          StudentValidator

          namespace HelloApi.Validations
          {
          public class StudentValidator : AbstractValidator<Student>
          {
          public StudentValidator()
          {
          RuleFor(s => s.Id).InclusiveBetween(1,10).WithMessage("id需要在1和10之間");
          }
          }
          }

          ASP.NET Core Getting Started:https://docs.fluentvalidation.net/en/latest/aspnet.html

          dotnet add package FluentValidation.AspNetCore

          ConfigureServices

          單個(gè)添加

          services.AddControllers()
          .AddFluentValidation();

          // 通過依賴注入的方式(單個(gè)添加)
          services.AddTransient, StudentValidator>();

          全部添加

          // 通過掃描程序集的方式(全部添加)
          services.AddControllers()
          .AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining());

          返回?cái)?shù)據(jù)處理

          • 返回?cái)?shù)據(jù)類型

          • 格式化響應(yīng)數(shù)據(jù)

          返回?cái)?shù)據(jù)類型

          ASP.NET Core Web API 中控制器操作的返回類型:https://docs.microsoft.com/zh-cn/aspnet/core/web-api/action-return-types?view=aspnetcore-5.0

          • 特定類型

          • IActionResult

          • ActionResult

          特定類型:最簡(jiǎn)單的操作返回基元或復(fù)雜數(shù)據(jù)類型(如 string 或自定義對(duì)象類型)

          IActionResult:常見返回類型為 BadRequestResult (400)、NotFoundResult (404) 和 OkObjectResult (200)

          [HttpPost]
          [Route("option/body")]
          public IActionResult CreateOption([FromBody] Student student)
          {
          if (!ModelState.IsValid)
          {
          return ValidationProblem();
          }

          //return BadRequest();

          //return NotFound();

          return Ok(student);
          }

          格式化響應(yīng)數(shù)據(jù)

          設(shè)置 ASP.NET Core Web API 中響應(yīng)數(shù)據(jù)的格式:https://docs.microsoft.com/zh-cn/aspnet/core/web-api/advanced/formatting?view=aspnetcore-5.0

          瀏覽器和內(nèi)容協(xié)商

          services.AddControllers(options =>
          {
          options.RespectBrowserAcceptHeader = true;// 瀏覽器和內(nèi)容協(xié)商
          });

          添加 XML 格式支持

          services.AddControllers(options =>
          {
          options.RespectBrowserAcceptHeader = true; // 瀏覽器和內(nèi)容協(xié)商
          })
          .AddXmlSerializerFormatters() // 添加 XML 格式支持
          .AddFluentValidation();

          啟動(dòng)程序,添加 XML Headers 訪問:

          添加基于 Newtonsoft.Json 的 JSON 格式支持

          添加 nuget 包:Microsoft.AspNetCore.Mvc.NewtonsoftJson

          services.AddControllers(options =>
          {
          options.RespectBrowserAcceptHeader = true; // 瀏覽器和內(nèi)容協(xié)商
          })
          .AddNewtonsoftJson()// 添加基于 Newtonsoft.Json 的 JSON 格式支持
          .AddXmlSerializerFormatters() // 添加 XML 格式支持
          .AddFluentValidation();

          GitHub源碼鏈接:

          https://github.com/MINGSON666/Personal-Learning-Library/tree/main/ArchitectTrainingCamp/HelloApi

          課程鏈接

          .NET云原生架構(gòu)師訓(xùn)練營講什么,怎么講,講多久


          歡迎各位讀者加入微信群一起學(xué)習(xí)交流,
          在公眾號(hào)后臺(tái)回復(fù)“加群”即可~~


          瀏覽 76
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          評(píng)論
          圖片
          表情
          推薦
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  久操av在线 | 夜夜操夜夜操夜夜操 | 国产内射ⅹxⅹx在线 | 在线观看欧美日韩视频 | 豆花精品在线视频 |