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();
        }
    }
  1. mvc主要使用的中间件是EndpointRouteMiddleware和EndpointMiddleware。通过applicationbuilder.UseRouting(),UseEndpoints()这个通过endpointRouteBuilder中的MapControllers()来实现对controller和action方法的注册。
  2. 注册上面两个中间件要使用服务。先注册相关服务。通过host.ConfigureServices(),IservicesCollection添加。AddRouting(),AddControllersWithViews()
  3. 添加视图,Views/{ContollerName}/{AciontName}.这样添加默认打开的视图。
posted @ 2022-05-05 21:29  vba是最好的语言  阅读(25)  评论(0编辑  收藏  举报