ASP.NET Core MVC(一)
ASP.NET Core MVC(我的第一个.NET Core项目):
开发工具:vs2017
创建
选择ASP.NET Core应用程序
以Core2.2为例,选择空模板
项目创建完成后如上图.
appsetting.json是配置文件
Program.cs和Startup.cs是项目的启动和配置文件,我们看Program.cs里的代码,
有个和控制台一样的Main方法,项目运行后会执行这个方法里的代码,调用CreateWebHostBuilder(),CreateWebHostBuilder()又会去找Startup。。。Startup.cs有两个方法
所以程序跑起来会执行ConfigureServices()和Configure()方法,我们直接运行代码,可以看到 Hello World!
就是Configure()里的代码,接下来,我们写一个接口,然后用类来继承它,给大家显示一个字符串!!!
首先创建一个接口
然后在新建一个类去继承接口,有一个GetAll()方法,返回一个字符串
然后在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);
});
}
}
}
然后运行,会报错,如下图
意思就是Configure()第三个我们自定义的接口参数找不到,因为没有注册,这里我们就需要用上面的ConfigureServices()方法进行注册,注册的方法代码有三种,下图:
三者的区别大家可以看一下这个文章
https://blog.csdn.net/loongsking/article/details/79964352
注册成功之后,就可以运行,我们可以看到下图,就成功了
推荐阅读
-
ASP.NET Core MVC(一)
-
ASP.NET MVC5 ModelBinder
-
从零开始实现ASP.NET Core MVC的插件式开发(六) - 如何加载插件引用
-
从零开始学习 ASP.NET MVC 1.0 (四) View/Model 全解 【转】
-
从零开始实现ASP.NET Core MVC的插件式开发(四) - 插件安装
-
ASP.NET MVC3 实现全站重定向的简单方法
-
.NET Core 1.0学习(4)粗略看了一下ASP.NET Core MVC例子
-
asp.net core mvc 表单太重
-
asp.net core mvc 入门demo
-
[Asp.net mvc]URL 路由 读书笔记