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)

以上这些均是我学习的总结,希望能帮到大家,如果有错误的地方,也欢迎大家的指出。

发布了49 篇原创文章 · 获赞 18 · 访问量 4343

猜你喜欢

转载自blog.csdn.net/asd0356/article/details/104199150