ASP.NET Core MVC基礎知識

首先看看一個最基本的asp.net core mvc項目裏面所含有的骨架:
在這裏插入圖片描述
接下來我按照程序執行順序來分別敘述。
Program.cs:
這個文件裏面有Main函數,所以它是程序最先開始的地方。
這個類的主要作用就是啓動主機,包括注入Startup。
以下就是一個Program.cs文件的代碼

using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;

namespace Tutorial.Web
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>();
    }
}

Startup.cs:
這個文件裏面默認有兩個函數:
ConfigureServices(IServiceCollection services) 和
Configure( IApplicationBuilder app, IHostingEnvironment env)

ConfigureServices :這個方法通過services對象實現此項目需要進行的依賴注入。
Configure:這個方法用app對象配置各種功能的中間件,env對象來獲取開發環境。
以下就是一個Startup.cs文件的代碼

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Tutorial.Web.Data;
using Tutorial.Web.Model;
using Tutorial.Web.Services;

namespace Tutorial.Web
{
    public class Startup
    {
        //IConfiguration在Program的CreateDefaultBuilder方法中以及註冊好了
        private readonly IConfiguration _configuration;

        public Startup(IConfiguration configuration)
        {
            _configuration = configuration;
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.AddDbContext<DataContext>(options =>
            {
                options.UseSqlServer(_configuration.GetConnectionString("DefaultConnection"));
            });
            services.AddSingleton<IWelcomeService, WelcomeService>();
            //每次http請求會產生一個新的實例 AddScoped
            services.AddScoped<IRepository<Student>, EFCoreRepository>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(
            IApplicationBuilder app,
            IHostingEnvironment env,
            IWelcomeService welcomeService)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler();
            }
            //調用wwwroot裏面的文件
            app.UseStaticFiles();
            app.UseMvc(builder =>
            {
                // /Home/Index/3
                builder.MapRoute("Default", "{controller=Home}/{action=Index}/{id?}");
            });
            //app.UseMvcWithDefaultRoute();

            app.Run(async (context) =>
            {
                var welcome = welcomeService.GetMessage();
                await context.Response.WriteAsync(welcome);
            });
        }
    }

    public interface IWelcomeService
    {
        string GetMessage();
    }

    public class WelcomeService : IWelcomeService
    {
        public string GetMessage()
        {
            return "Hello from IWelcome service";
        }
    }
}

注:上述代碼的IWelcomeService 在ConfigureServices方法進行注入,然後就能在Configure方法內進行使用。
appsettings.json:
這個文件是一個配置文件,主要配置包括日誌,數據庫連接等信息。
wwwroot:
這個文件是一個靜態配置文件,包括css,js,image等文件
(引用這個文件需要在Startup裏進行相應的中間件配置)
Models:
模型層,在這裏定義所需要的基本數據模型。(如student)
Data:
它包裝Model層的數據信息並與數據庫相聯繫。
Controllers:
控制層,通過依賴注入可以獲取Data層的數據並調用自己的業務邏輯,最後返回(對象)給視圖層。
Views:
視圖層,通過控制層傳入的數據來渲染頁面。
這裏我附上一張自己繪製的程序流程圖,大家僅供參考:
在這裏插入圖片描述
接下來,敘述一些更細節的東西。
cshtml文件:
這種文件是在View層下最常用的文件,它之所以是cshtml文件,首先它是一個html文件並且它裏面還能編寫C#代碼。(可以類比Javaweb的jsp文件)
它裏面也有很多自己特定的語法:
@model:cshtml頁面中的指令符(提供一些信息,讓View試圖能夠正確的構造代碼(智能提示))
@:後接cs代碼
Model:從·Controller傳來的對象
以下就是一個Detail.cshtml文件的代碼

@model Tutorial.Web.Model.Student

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <title>Detail</title>
</head>
<body>
<div>
    <h1>學生信息</h1>
    <h2>ID:@Model.Id</h2>
    <div>
        姓名:@Model.FirstName @Model.LastName
    </div>
    <div>
        性別:@Model.Gender
    </div>
    <div>
        出生日期:@Model.BirthdayDate.ToString("yyyy-MM-dd")
    </div>

    <a asp-action="Index">返回到Home</a>
</div>
</body>
</html>

細心的夥伴應該會發現這個文件裏面除了有上述描述語法外還有一個asp-action,這是什麼玩意?
Tag Helpers:
它就是Tag Helpers,也叫標記幫助程序。簡單來說,它高效的可以便於html頁面的開發例如自動在運行後補全代碼。
以上述代碼爲例,它還可以用另外兩種代碼表示,只是更復雜而言。
嵌入a標籤:<a href="/Home/Detail/@s.Id">Detail</a>
使用@Html裏的方法:@Html.ActionLink("Detail","Detail",new{id = s.Id});
使用Tag Helpers:<a asp-action="Detail" asp-route-id="@s.Id">Detail</a>(推薦)
注意:在使用Tag Helpers前需要提前在_ViewImports.cshtm文件中進行引用Tag Helpers。
最後,還有幾個常見的cshtml文件,這裏我只簡單的敘述它們的功能。
_Layout.cshtml:外層模板(頁面通過代碼塊引入Layout,@RenderBody()表示動態的被引入頁面代碼(body裏的代碼))
_ViewStart.cshtml:(最先執行的View的代碼)放置一些重複的代碼
_ViewImports.cshtml:放置一些重複的引用(例如Tag Helpers)

以上這些均是我學習的總結,希望能幫到大家,如果有錯誤的地方,也歡迎大家的指出。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章