Asp.NetCore 从控制台到WebApi
一、新建一个.NetCore控制台程序
二、添加依赖项
三、添加Startup.cs文件
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using System; using System.Collections.Generic; using System.Text; namespace ConsoleWeb { public class Startup { public void Configure(IApplicationBuilder app) { app.Run(context => { return context.Response.WriteAsync("Hello world"); }); } } }
四、Program.cs文件添加 Microsoft.AspNetCore.Hosting 引用,创建WebHost对象
using Microsoft.AspNetCore.Hosting; using System; using System.IO; namespace myFirstConsoleDemo { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!"); var host = new WebHostBuilder() .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseStartup<Startup>() .Build(); host.Run(); } } }
五、运行
浏览器输入localhost;5000
六、加入WebApi
项目根目录下添加一个Api文件夹用来放Api,在Api中新建一个TestApi.cs 继承自ControllerBase
using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Text; namespace ConsoleWeb.Api { public class TestApi:ControllerBase { [Route("test/index")] public string Index() { return "hello api"; } } }
Startup.cs中加入ConfigureServices方法
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; using System.Text; namespace ConsoleWeb { public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddMvc(); } public void Configure(IApplicationBuilder app) { app.UseMvc(s=> { s.MapRoute("default", "{controller}/{action}/{id?}", "test/index"); }); app.Run(context => { return context.Response.WriteAsync("Hello world"); }); } } }
运行程序、在浏览器地址栏中输入localhost:5000/test/index
七、添加页面,搭建webMVC application
编辑 .csproj文件
到HomeController.cs文件中 选中要添加视图的Action
添加成功后会自动引入以下几个NuGet包
现在运行 就可以看到页面了