当前位置:网站首页>Asp.Net Core learning notes: Introduction

Asp.Net Core learning notes: Introduction

2020-11-06 01:39:01 itread01

# Asp.Net Core Learning Based on .Net Core 2.2 Version of learning notes . ## Common sense image Django That automatically checks for code updates , Automatic overload server ( It's so convenient ) ``` dotnet watch run ``` ## Hosting settings Set the project file `AspNetCoreHostingModel` Properties . ```xml netcoreapp2.2 InProcess ``` - InProcess: Use IIS Server hosting - OutOfProcess: Use your own Kestrel Server hosting ## Introduction to intermediary software - Can be accessed and requested at the same time - After the request can be processed , Pass the request to the next mediation Software - After the request can be processed , Short circuit the pipe - You can send out a response - The mediation software is executed in the order of addition By means of `Configure` New arguments in `ILogger logger` introduce Asp.Net Core Self contained log element . ```c# public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILogger logger) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseStaticFiles(); app.Use(async (context, next) => { context.Response.ContentType = "text/plain;charset=utf-8"; //await context.Response.WriteAsync("Hello!"); logger.LogDebug("M1: Incoming requests "); await next(); logger.LogDebug("M1: Outgoing response "); }); app.Use(async (context, next) => { context.Response.ContentType = "text/plain;charset=utf-8"; logger.LogDebug("M2: Incoming requests "); await next(); logger.LogDebug("M2: Outgoing response "); }); app.Run(async (context) => { //await context.Response.WriteAsync(" Hello !"); await context.Response.WriteAsync("M3: Process request , Generate response "); logger.LogDebug("M3: Process request , Generate response "); }); } ``` Output log :( Three mediators can see the execution of the software ) ``` Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request starting HTTP/2.0 GET https://localhost:44383/ StudyManagement.Startup:Debug: M1: Incoming requests StudyManagement.Startup:Debug: M2: Incoming requests StudyManagement.Startup:Debug: M3: Process request , Generate response StudyManagement.Startup:Debug: M2: Outgoing response StudyManagement.Startup:Debug: M1: Outgoing response Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 52.8954ms 200 text/plain;charset=utf-8 StudyManagement.Startup:Debug: M1: Incoming requests StudyManagement.Startup:Debug: M2: Incoming requests StudyManagement.Startup:Debug: M3: Process request , Generate response StudyManagement.Startup:Debug: M2: Outgoing response StudyManagement.Startup:Debug: M1: Outgoing response Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 34.3387ms 200 text/plain;charset=utf-8 ``` ## Static file support All static files are in the directory `wwwroot` Next ### First ```c# // Set default file // If not set , The presupposition is index.html/default.html These var defaultFileOpinions = new DefaultFilesOptions(); defaultFileOpinions.DefaultFileNames.Clear(); defaultFileOpinions.DefaultFileNames.Add("test.html"); // Add default file intermediary software , Must be on UseStaticFiles Before registration app.UseDefaultFiles(defaultFileOpinions); // New static file mediation Software app.UseStaticFiles(); ``` ### DirectoryBrowser Intermediary software You can browse through the browser `wwwroot` What's under . It is not recommended to use in a production environment . ```c# app.UseDirectoryBrowser(); ``` ### FileServer Intermediary software Integrated `UseDefaultFiles`, `UseStaticFiles`, `UseDirectoryBrowser` The functions of the three intermediary software . It is also not recommended for use in production environments . ```c# var fileServerOpinions = new FileServerOptions(); fileServerOpinions.DefaultFilesOptions.DefaultFileNames.Clear(); fileServerOpinions.DefaultFilesOptions.DefaultFileNames.Add("test.html"); app.UseFileServer(fileServerOpinions); ``` ## Developer exception page ```c# if (env.IsDevelopment()) { var developerExceptionPageOptions = new DeveloperExceptionPageOptions(); // Shows the number of lines of code developerExceptionPageOptions.SourceCodeLineCount = 10; app.UseDeveloperExceptionPage(); } app.Run(async (context) => { throw new Exception(" The exception of throwing oneself "); }); ``` ## Development environment variables - Development: Development environment - Staging: demonstration ( Simulation 、 Temporary ) The environment - Production: formal ( To produce ) The environment Ops: - Use `ASPNETCORE_ENVIRONMENT` The environment variable sets the development environment . - On the development machine , stay `launchSettings.json` Set environment variables in the file . - stay Staging and Production Environmental time , Try to set environment variables in the operating system . - Use `IHostEnvironment` Service access execution time environment - In addition to the standard environment, it also supports custom environment (UAT、QA etc. ) ## introduce MVC frame ### First add MVC Service . ```c# public void ConfigureServices(IServiceCollection services) { // Simply introduce the core MVC Service , Only core functions services.AddMvcCore(); // This is usually used , Multi function services.AddMvc(); } ``` ### New intermediary software ```c# public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILogger logger) { if (env.IsDevelopment()) { var developerExceptionPageOptions = new DeveloperExceptionPageOptions(); // Shows the number of lines of code developerExceptionPageOptions.SourceCodeLineCount = 10; app.UseDeveloperExceptionPage(); } app.UseStaticFiles(); app.UseMvcWithDefaultRoute(); } ``` MVC Routing rules :`/ Controller name / Method name `,( Case insensitive ) For example, the route in the following example is :`/home/index` ### HomeController Code : ```c# public class HomeController : Controller { public string Index() { return "home controller"; } } ``` ## Preliminary understanding of model and dependency injection ### Define the model ```c# public class Student { public int Id { get; set; } public string Name { get; set; } public string ClassName { get; set; } public string Email { get; set; } } ``` ### Define the interface ```c# public interface IStudentRepository { Student GetById(int id); void Save(Student student); } ``` ### Implementation interface No access to the database yet , Define a class of fake data ```c# public class MockStudentRepository : IStudentRepository { private List _students; public MockStudentRepository() { _students = new List { new Student { Id=1, Name=" millet ", ClassName=" Red rice ", Email=" [email protected]" }, new Student { Id=2, Name=" Huawei ", ClassName=" Glory ", Email=" [email protected]" }, new Student { Id=3, Name="oppo", ClassName="vivo", Email=" [email protected]" }, }; } public Student GetById(int id) { return _students.FirstOrDefault(a => a.Id == id); } public void Save(Student student) => throw new NotImplementedException(); } ``` ### Register dependency injection Asp.Net Core There are three types of dependency injection container registration services - AddSingleton - AddTransient - AddScoped The advantages of dependency injection - Low coupling - High testability , More convenient for unit testing ```c# public void ConfigureServices(IServiceCollection services) { services.AddMvc(); // Register dependency injection , Bind the implementation class to the interface services.AddSingleton (); } ``` ### Using dependency injection in the model ```c# public class StudentController : Controller { private readonly IStudentRepository _studentRepository; // Inject by means of constructor injection IStudentRepository public StudentController(IStudentRepository studentRepository) { _studentRepository = studentRepository; } public JsonResult Index(int id) { return Json(_studentRepository.GetById(id)); } } ``` ## Introduction to controller ### Content format negotiation Use in controller method `ObjectResult` Return type , Support content negotiation , Returns data according to the request header argument , ```c# // Support content format negotiation public ObjectResult Details(int id) { return new ObjectResult(_studentRepository.GetById(id)); } ``` Such as : ``` Accept: application/xml ``` Will return to xml Format . notes : We need to add more xml Serializer . ```c# public void ConfigureServices(IServiceCollection services) { services.AddMvc() // Register XML Serializer .AddXmlSerializerFormatters(); } ``` ## Look at the basics ### The method of passing data from the controller to the view The first two are weak types - ViewData - ViewBag - Strong type view ### ViewData - Weakly typed dictionary objects - Use string The key value of the type , Storage and chaxun - Dynamic parsing at execution time - There is no intellectual perception , There is no type checking at compile time Usage method : ```c# ViewData["Title"] = " Students review "; ViewData["Model"] = model; ``` cshtml Code : ```scss

@ViewData["Title"]

@{ var student = ViewData["model"] as StudyManagement.Models.Student; }
full name :@student.Name
Class :@student.ClassName
``` ### ViewBag ```c# // Assign values directly to dynamic properties ViewBag.PageTitle = "ViewBag Title "; ViewBag.Student = model; ``` cshtml Use : ```html

@ViewBag.PageTitle

full name :@ViewBag.Student.Name
Class :@ViewBag.Student.ClassName
``` ### Strong type view Send to in the controller View() Model ```c# public IActionResult GetView() { var model = _studentRepository.GetById(1); return View(model); } ``` stay cshtml The model type specified in the ```scss @model StudyManagement.Models.Student

Strong type model

  • @Model.Id
  • @Model.Name
  • @Model.ClassName
  • @Model.Email
``` ## ViewModel View model Similar to DTO( Data transmission object ) ### Define ViewModel ```c# public class StudentDetailsViewModel { public Student Student { get; set; } public string PageTitle { get; set; } } ``` ### Modify controller ```c# public IActionResult Details() { var model = _studentRepository.GetById(1); var viewModel = new StudentDetailsViewModel { Student = model, PageTitle = "viewmodel Page title in " }; return View(viewModel); } ``` ### stay View Use in ```scss @model StudyManagement.ViewModels.StudentDetailsViewModel

Strong type model

@Model.PageTitle

  • @Model.Student.Id
  • @Model.Student.Name
  • @Model.Student.ClassName
  • @Model.Student.Email
``` ### View Use loop in ```scss @model IEnumerable @foreach (var student in Model) { }
Id full name Class Email
@student.Id @student.Name @student.ClassName @student.Email
``` ## Layout view LayoutView ### Create layout view ```scss @ViewBag.Title
@RenderBody()
@RenderSection("Scripts", required: false) ``` ### Rendering view ```scss @model IEnumerable @{ Layout = "~/Views/Shared/_Layout.cshtml"; ViewBag.Title = " Home Student list "; }
``` ### View nodes Section Render nodes in layout view ```scss @RenderSection("Scripts", required: false) ``` Define nodes in the normal view ```scss @section Scripts{ } ``` ### Inspection begins ViewStart My understanding is that `_ViewStart.cshtml` Each view file in the directory where the file is located starts rendering. First run the contents of this file . It is usually placed directly in the `Views` Under the catalogue , Global effect , It can be placed under each sub folder , This can cover the global `_ViewStart.cshtml`. ```scss @{ Layout = "_Layout"; } ``` ### View import ViewImports Used to import the namespace 、 Registration model and so on n Multiple operations . Effective mechanism and ViewStart almost . ## route - Regular routing ( Traditional routing ) - Attribute routing ### Regular routing stay `MapRoute` Just pass in the method . ```c# // Custom route app.UseMvc(route =>route.MapRoute("default", "{controller=Home}/{action=Index}/{id?}")); ``` ### Attribute routing More flexible than traditional routing , It can be used with traditional routing . That is to add a routing annotation to the controller method , A method can map multiple routes at the same time . ```c# [Route("Home/Index")] public IActionResult Index() { return View(_studentRepository.GetAll()); } ``` Arguments can also be specified in the route ```c# [Route("test/{id?}")] public IActionResult Details(int id = 1) { var model = _studentRepository.GetById(id); var viewModel = new StudentDetailsViewModel { Student = model, PageTitle = "viewmodel Page title in " }; return View(viewModel); } ``` You can annotate the controller class directly ,`[controller]/[action]`. ## Welcome to exchange Please leave a message in the background of wechat public account for communication problems , I will reply to every piece of information ~ - Wechat public account : Star painting master - Play code studio :[https://live.bilibili.com/11883038](https://live.bilibili.com/11883038) - You know :[https://www.zhihu.com/people/dealiaxy](https://www.zhihu.com/people/dealiaxy) - Column :[https://zhuanlan.zhihu.com/deali](https://zhuanlan.zhihu.co

版权声明
本文为[itread01]所创,转载请带上原文链接,感谢