在本章中,我们将在FirstAppDemo应用程序中设置MVC框架。 我们将在ASP.NET Core之上构建一个Web应用程序,更具体地说,是ASP.NET Core MVC框架。 我们可以在技术上只使用中间件构建一个完整的应用程序,但ASP.NET Core MVC为我们提供了我们可以用来轻松创建HTML页面和基于HTTP的API的功能。
要在我们的空项目中设置MVC框架,请按照下列步骤操作:
-
安装Microsoft.AspNet.Mvc包,它允许我们访问框架提供的程序集和类。
-
包安装完成后,我们需要注册ASP.NET MVC在运行时需要的所有服务。 我们将在ConfigureServices方法内部执行此操作。
-
最后,我们需要为ASP.NET MVC添加中间件以接收请求。 这件中间件基本上接受一个HTTP请求,并尝试将该请求定向到我们将要写的C#类。
第1步 - 让我们通过右键单击管理NuGet包到NuGet包管理器。 安装Microsoft.AspNet.Mvc包,它允许我们访问框架提供的程序集和类。
步骤2 - 安装Microsoft.AspNet.Mvc软件包后,我们需要注册ASP.NET Core MVC在运行时需要的所有服务。 我们将使用ConfigureServices方法执行此操作。 我们还将添加一个简单的控制器,我们将看到该控制器的一些输出。
让我们给这个项目添加一个新文件夹,并称之为Controllers。 在此文件夹中,我们可以放置多个控制器,如下所示。
现在右键单击Controllers文件夹并在菜单中选择Add→Class。
第3步 - 在这里我们要添加一个简单的C#类,并为此类取名HomeController,然后单击添加按钮,如上面的截图。
这将是我们的默认页面。
步骤4 - 让我们定义一个单一的公共方法,返回一个字符串,并调用该方法Index如下面的程序所示。
1
2
3
4
5
6
7
8
9
10
11
|
using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Threading.Tasks;
namespace
FirstAppdemo.Controllers {
public
class
HomeController {
public
string
Index() {
return
"Hello, World! this message is from Home Controller..."
;
}
}
}
|
步骤5 - 当您转到网站的根目录时,您想要查看控制器响应。 现在,我们将为我们的index.html文件提供服务。
让我们进入网站的根目录并删除index.html。 我们希望控制器对请求作出响应而不是index.html文件来响应。
步骤6 - 现在转到启动类中的Configure方法,并添加UseMvcWithDefaultRoute中间件。
步骤7 - 现在刷新网站的根目录。
您将遇到500错误。 错误说明框架无法找到所需的ASP.NET Core MVC服务。
ASP.NET核心框架本身由具有非常集中的责任的不同的小组件组成。
例如,有一个组件必须定位和实例化控制器。
该组件需要在ASP.NET Core MVC的服务集合中才能正常运行。
步骤8 - 除了添加NuGet包和中间件之外,我们还需要在ConfigureServices中添加AddMvc服务。 这里是Startup类的完整实现。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
|
using
Microsoft.AspNet.Builder;
using
Microsoft.AspNet.Hosting;
using
Microsoft.AspNet.Http;
using
Microsoft.Extensions.DependencyInjection;
using
Microsoft.Extensions.Configuration;
namespace
FirstAppDemo {
public
class
Startup {
public
Startup() {
var builder =
new
ConfigurationBuilder() .AddJsonFile(
"AppSettings.json"
);
Configuration = builder.Build();
}
public
IConfiguration Configuration {
get
;
set
; }
// 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,
public
void
ConfigureServices(IServiceCollection services) {
services.AddMvc();
}
// This method gets called by the runtime.
// Use this method to configure the HTTP request pipeline.
public
void
Configure(IApplicationBuilder app) {
app.UseIISPlatformHandler();
app.UseDeveloperExceptionPage();
app.UseRuntimeInfoPage();
app.UseFileServer();
app.UseMvcWithDefaultRoute();
app.Run(async (context) => {
var msg = Configuration[
"message"
];
await context.Response.WriteAsync(msg);
});
}
// Entry point for the application.
public
static
void
Main(
string
[] args) => WebApplication.Run<Startup>(args);
}
}
|
步骤9 - 保存Startup.cs文件,并转到浏览器并刷新。 您现在将收到我们的Home控制器的回复。
本文标题: Asp.Net Core 设置MVC
本文地址:http://www.yuanjiaocheng.net/ASPNET-CORE/setup-mvc.html