HelloMVC --net core
修改成mvc的代码如下:
static void Main(string[] args) { Host.CreateDefaultBuilder() .ConfigureWebHostDefaults(WebHostBuilder => WebHostBuilder //.UseKestrel() .ConfigureServices(services => services.AddRouting() .AddControllersWithViews() //services.AddControllerWithViews() ) .Configure(app => app.UseRouting() .UseEndpoints(endpointRouteBuilder => endpointRouteBuilder.MapControllers() ))) .Build() .Run(); } } public class HelloController : Controller { [HttpGet("/hello/{name}")] public IActionResult SayHello(string name) { ViewBag.name = name; return View(); } }
- mvc主要使用的中间件是EndpointRouteMiddleware和EndpointMiddleware。通过applicationbuilder.UseRouting(),UseEndpoints()这个通过endpointRouteBuilder中的MapControllers()来实现对controller和action方法的注册。
- 注册上面两个中间件要使用服务。先注册相关服务。通过host.ConfigureServices(),IservicesCollection添加。AddRouting(),AddControllersWithViews()
- 添加视图,Views/{ContollerName}/{AciontName}.这样添加默认打开的视图。