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

Asp.Net Core learning notes: Introduction

2020-11-06 01:15:10 Master of Star Painting

Asp.Net Core Study

be based on .Net Core 2.2 Version of learning notes .

common sense

image Django That automatically checks for code updates , Auto reload server ( It's so convenient )

dotnet watch run

Hosting settings

Set the AspNetCoreHostingModel attribute .

<PropertyGroup>
    <TargetFramework>netcoreapp2.2</TargetFramework>
    <AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>
</PropertyGroup>
  • InProcess: Use IIS Server hosting
  • OutOfProcess: Use your own Kestrel Server hosting

Introduction to middleware

  • Can be accessed and requested at the same time
  • After the request can be processed , Pass the request to the next middleware
  • After the request can be processed , Short circuit the pipe
  • The response can be sent out
  • The middleware is executed in the order of addition

By means of Configure Add parameters in ILogger<Startup> logger introduce Asp.Net Core Self contained log component .

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILogger<Startup> 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 request  ");
        await next();
        logger.LogDebug("M1:  Outgoing response ");
    });


    app.Use(async (context, next) =>
    {
        context.Response.ContentType = "text/plain;charset=utf-8";

        logger.LogDebug("M2:  incoming request  ");
        await next();
        logger.LogDebug("M2:  Outgoing response ");
    });

    app.Run(async (context) =>
    {
        //await context.Response.WriteAsync(" Hello !");
        await context.Response.WriteAsync("M3:  Processing requests , Generate response ");
        logger.LogDebug("M3:  Processing requests , Generate response ");
    });
}

Output log :( You can see the execution process of the three middleware )

Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request starting HTTP/2.0 GET https://localhost:44383/  
StudyManagement.Startup:Debug: M1:  incoming request  
StudyManagement.Startup:Debug: M2:  incoming request  
StudyManagement.Startup:Debug: M3:  Processing requests , 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 request  
StudyManagement.Startup:Debug: M2:  incoming request  
StudyManagement.Startup:Debug: M3:  Processing requests , 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

//  Set default file 
//  If it is not set , The default is index.html/default.html These are a few 
var defaultFileOpinions = new DefaultFilesOptions();
defaultFileOpinions.DefaultFileNames.Clear();
defaultFileOpinions.DefaultFileNames.Add("test.html");

//  Add default file Middleware , Must be in UseStaticFiles Previous registration 
app.UseDefaultFiles(defaultFileOpinions);

//  Add static file Middleware 
app.UseStaticFiles();

DirectoryBrowser middleware

It can be browsed in the browser wwwroot Below . Not recommended for use in production environments .

app.UseDirectoryBrowser();

FileServer middleware

Integrated UseDefaultFiles, UseStaticFiles, UseDirectoryBrowser Functions of three Middleware . It is also not recommended for use in production environments .

var fileServerOpinions = new FileServerOptions();
fileServerOpinions.DefaultFilesOptions.DefaultFileNames.Clear();
fileServerOpinions.DefaultFilesOptions.DefaultFileNames.Add("test.html");

app.UseFileServer(fileServerOpinions);

Developer exception page

if (env.IsDevelopment())
{
    var developerExceptionPageOptions = new DeveloperExceptionPageOptions();
    //  Displays the number of lines of code 
    developerExceptionPageOptions.SourceCodeLineCount = 10;
    app.UseDeveloperExceptionPage();
}

app.Run(async (context) =>
{
    throw new Exception(" Exception thrown by oneself ");
});

Development environment variables

  • Development: development environment
  • Staging: demonstration ( simulation 、 temporary ) Environmental Science
  • Production: formal ( production ) Environmental Science

Ops:

  • Use ASPNETCORE_ENVIRONMENT Environment variable setting development environment .
  • On the development machine , stay launchSettings.json Setting environment variables in file .
  • stay Staging and Production Environmental time , Try to set environment variables in the operating system .
  • Use IHostEnvironment Service access runtime environment
  • In addition to custom environments, standards are also supported (UAT、QA etc. )

introduce MVC frame

First add MVC service .

public void ConfigureServices(IServiceCollection services)
{
    //  Simply introduce the core MVC service , Only core functions 
    services.AddMvcCore();
    //  This is usually used , Multi function 
    services.AddMvc();
}

Add Middleware

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILogger<Startup> logger)
{
    if (env.IsDevelopment())
    {
        var developerExceptionPageOptions = new DeveloperExceptionPageOptions();
        //  Displays 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 :

public class HomeController : Controller
{
    public string Index()
    {
        return "home controller";
    }
}

Preliminary understanding of model and dependency injection

Defining models

public class Student
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string ClassName { get; set; }
    public string Email { get; set; }
}

Defining interfaces

public interface IStudentRepository
{
    Student GetById(int id);
    void Save(Student student);
}

Implementation interface

There is no access to the database , Define a class of fake data

public class MockStudentRepository : IStudentRepository
{
    private List<Student> _students;

    public MockStudentRepository()
    {
        _students = new List<Student>
        {
            new Student { Id=1, Name=" millet ", ClassName=" Red rice ", Email="hello1@deali.cn" },
            new Student { Id=2, Name=" Huawei ", ClassName=" glory ", Email="hello2@deali.cn" },
            new Student { Id=3, Name="oppo", ClassName="vivo", Email="hello3@deali.cn" },
        };
    }

    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

Advantages of dependency injection

  • Low coupling
  • High testability , More convenient for unit testing
public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    //  Register dependency injection , Bind the implementation class to the interface 
    services.AddSingleton<IStudentRepository, MockStudentRepository>();
}

Using dependency injection in the model

public class StudentController : Controller
{
    private readonly IStudentRepository _studentRepository;

    //  It is injected by 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 , Return data according to request header parameters ,

//  Support content format negotiation 
public ObjectResult Details(int id)
{
    return new ObjectResult(_studentRepository.GetById(id));
}

Such as :

Accept: application/xml

Will return xml Format . notes : Also add xml Serializer .

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc()
        //  register XML Serializer 
        .AddXmlSerializerFormatters();
}

Getting started with views

Methods to transfer data from controller to view

The first two are weak types

  • ViewData
  • ViewBag
  • Strongly typed view

ViewData

  • Weakly typed dictionary object
  • Use string The key value of the type , Storage and chaxun
  • Runtime dynamic parsing
  • No IntelliSense , There is also no type checking at compile time

Usage method :

ViewData["Title"] = " Student view ";
ViewData["Model"] = model;

cshtml Code :

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
    <h1>@ViewData["Title"]</h1>
    @{
        var student = ViewData["model"] as StudyManagement.Models.Student;
    }
    <div> full name :@student.Name</div>
    <div> class :@student.ClassName</div>
</body>
</html>

ViewBag

//  Assign values directly to dynamic properties 
ViewBag.PageTitle = "ViewBag title ";
ViewBag.Student = model;

cshtml Use :

<h1>@ViewBag.PageTitle</h1>
<div> full name :@ViewBag.Student.Name</div>
<div> class :@ViewBag.Student.ClassName</div>

Strongly typed view

In the controller to View() Model

public IActionResult GetView()
{
    var model = _studentRepository.GetById(1);
    return View(model);
}

stay cshtml The model type is specified in

@model StudyManagement.Models.Student
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
    <h1> Strongly typed model </h1>
    <ul>
        <li>@Model.Id</li>
        <li>@Model.Name</li>
        <li>@Model.ClassName</li>
        <li>@Model.Email</li>
    </ul>

</body>
</html>

ViewModel Model view

Be similar to DTO( Data transmission object )

Definition ViewModel

public class StudentDetailsViewModel
{
    public Student Student { get; set; }
    public string PageTitle { get; set; }
}

Modify controller

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

<!--  The registered model here is changed to ViewModel 了  -->
@model StudyManagement.ViewModels.StudentDetailsViewModel
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
    <h1> Strongly typed model </h1>
    <h2>@Model.PageTitle</h2>
    <ul>
        <li>@Model.Student.Id</li>
        <li>@Model.Student.Name</li>
        <li>@Model.Student.ClassName</li>
        <li>@Model.Student.Email</li>
    </ul>
</body>
</html>

View Use cycle in

@model IEnumerable<StudyManagement.Models.Student>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
    <table border="1">
        <tr>
            <td>Id</td>
            <td> full name </td>
            <td> class </td>
            <td> mailbox </td>
        </tr>
        @foreach (var student in Model)
        {
            <tr>
                <td>@student.Id</td>
                <td>@student.Name</td>
                <td>@student.ClassName</td>
                <td>@student.Email</td>
            </tr>
        }
    </table>
</body>
</html>

Layout view LayoutView

Create layout view

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
</head>
<body>
    <div>
        @RenderBody()
    </div>

    @RenderSection("Scripts", required: false)
</body>
</html>

Render view

@model IEnumerable<StudyManagement.Models.Student>
@{
    Layout = "~/Views/Shared/_Layout.cshtml";
    ViewBag.Title = " home page   Student list ";
}
<div></div>

View node Section

Render nodes in layout view

@RenderSection("Scripts", required: false)

Defining nodes in normal view

@section Scripts{ 
    <script>
        document.write("hello");
    </script>
}

View start ViewStart

My understanding is that _ViewStart.cshtml Each view file in the directory where the file is located starts rendering, and the contents of this file are executed first . It is usually placed directly in the Views Under the table of contents , Global effect , It can be placed under each sub folder , This can cover the global _ViewStart.cshtml.

@{
    Layout = "_Layout";
}

View import ViewImports

Used to import a namespace 、 Registration model, etc n Multiple operations .

Effective mechanism and ViewStart almost .

route

  • General routing ( Traditional routing )
  • Attribute routing

General routing

stay MapRoute Just pass in the method .

//  Custom routing 
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 routing annotation to the controller method , A method can map multiple routes at the same time .

[Route("Home/Index")]
public IActionResult Index()
{
    return View(_studentRepository.GetAll());
}

Parameters can also be specified in the route

[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

Exchange questions please leave a message at WeChat official account. , I will reply to every message ~

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