加一下试试:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseRouting(); app.UseEndpoints(endpoint => { endpoint.MapGet("http://www.likecs.com/", async context => { await context.Response.WriteAsync("Hello from Demo"); }); }); }这次运行,浏览器中就看到正确的输出了。
我们可以用MapGet映射更多资源:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseRouting(); app.UseEndpoints(endpoint => { endpoint.MapGet("http://www.likecs.com/", async context => { await context.Response.WriteAsync("Hello from Demo"); }); endpoint.MapGet("/test", async context => { await context.Response.WriteAsync("Hello from Demo.Test"); }); endpoint.MapGet("/about", async context => { await context.Response.WriteAsync("Hello from Demo.About"); }); }); }
到这儿,我们成功地把Console应用转为了Web应用。
三、延伸内容上面完成的Web应用,算是Web应用中的基础。基于这个内容,我们还可以扩展到别的项目结构。
1. 改为MVC应用需要在ConfigureServices 中注入AddControllersWithViews,并在Configure中添加MapDefaultControllerRoute:
public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseRouting(); app.UseEndpoints(endpoint => { endpoint.MapDefaultControllerRoute(); }); } } 2. 改为WebAPI应用需要注入AddControllers和MapControllers:
public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddControllers(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseRouting(); app.UseEndpoints(endpoint => { endpoint.MapControllers(); }); } } 3. 改为Razor应用需要注入AddRazorPages和MapRazorPages:
public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddRazorPages(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseRouting(); app.UseEndpoints(endpoint => { endpoint.MapRazorPages(); }); } } 四、总结看下来,其实过程很简单。通过这种方式,能更进一步理解Dotnet Core的项目结构以及应用的运行过程。
希望对大家能有所帮助。
本文的配套代码在:https://github.com/humornif/Demo-Code/tree/master/0038/demo
微信公众号:老王Plus