天天看点

ASP.NET Core MVC(一)

ASP.NET Core MVC(我的第一个.NET Core项目):

开发工具:vs2017

创建

ASP.NET Core MVC(一)

选择ASP.NET Core应用程序

ASP.NET Core MVC(一)

以Core2.2为例,选择空模板

ASP.NET Core MVC(一)

项目创建完成后如上图.

appsetting.json是配置文件

Program.cs和Startup.cs是项目的启动和配置文件,我们看Program.cs里的代码,

ASP.NET Core MVC(一)

有个和控制台一样的Main方法,项目运行后会执行这个方法里的代码,调用CreateWebHostBuilder(),CreateWebHostBuilder()又会去找Startup。。。Startup.cs有两个方法

ASP.NET Core MVC(一)

所以程序跑起来会执行ConfigureServices()和Configure()方法,我们直接运行代码,可以看到 Hello World!

ASP.NET Core MVC(一)

就是Configure()里的代码,接下来,我们写一个接口,然后用类来继承它,给大家显示一个字符串!!!

首先创建一个接口

ASP.NET Core MVC(一)

然后在新建一个类去继承接口,有一个GetAll()方法,返回一个字符串

ASP.NET Core MVC(一)

然后在Startup.cs的Configur()方法里去用一下,首先要给Configur()方法里在加一个参数,就是我们自定义的接口,然后把"Hello World!"换成变量,代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;

namespace CoreTest
{
    public class Startup
    {
        // 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)
        {
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env,IWelCome Wcome)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.Run(async (context) =>
            {
                var Servrice = Wcome.GetAll();
                await context.Response.WriteAsync(Servrice);
            });
        }
    }
}
           

然后运行,会报错,如下图

ASP.NET Core MVC(一)

意思就是Configure()第三个我们自定义的接口参数找不到,因为没有注册,这里我们就需要用上面的ConfigureServices()方法进行注册,注册的方法代码有三种,下图:

ASP.NET Core MVC(一)

三者的区别大家可以看一下这个文章

https://blog.csdn.net/loongsking/article/details/79964352

注册成功之后,就可以运行,我们可以看到下图,就成功了

ASP.NET Core MVC(一)

继续阅读