1、安装依赖
Microsoft.AspNet.WebApi
Microsoft.AspNet.WebApi.Owin
Microsoft.Owin.Hosting
Microsoft.Owin.Host.HttpListener
2、Startup.cs
using Owin; using Swashbuckle.Application; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http.Formatting; using System.Text; using System.Threading.Tasks; using System.Web.Http; namespace OwinTest { public class Startup { public void Configuration(IAppBuilder appBuilder) { HttpConfiguration config = new HttpConfiguration(); config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute(name: "DefaultApi", routeTemplate: "api/{controller}/{action}", defaults: new { id = RouteParameter.Optional } ); config .EnableSwagger(c => c.SingleApiVersion("v1", "A title for your API")) .EnableSwaggerUi(); //清除xml格式,使用json格式 config.Formatters.XmlFormatter.SupportedMediaTypes.Clear(); config.Formatters.Add(new JsonMediaTypeFormatter()); appBuilder.UseWebApi(config); } } }
3、program.cs
using Microsoft.Owin.Hosting; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OwinTest { class Program { static void Main(string[] args) { StartOptions options = new StartOptions(); options.Urls.Add("http://localhost:9095"); options.Urls.Add("http://127.0.0.1:9095"); options.Urls.Add(string.Format("http://{0}:9095", Environment.MachineName)); using (WebApp.Start<Startup>(options)) { Console.WriteLine("server started..."); Console.ReadLine(); } } } }
4、控制器
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web.Http; namespace OwinTest { public class Product { public string Name { get; set; } public string Price { get; set; } } [RoutePrefix("api/products")] public class ProductsController : ApiController { static List<Product> products = new List<Product>() { new Product(){Name="product1",Price="2.55"}, new Product(){Name="product2",Price="2.3"} }; [HttpGet] [Route("myget")] public IEnumerable<Product> Get() { return products; } [HttpGet] [Route("myget2")] public string Get(int id) { return JsonConvert.SerializeObject(products) + "|||||||||||||||||" + id; } } }
5、安装 swagger
Install-Package Swashbuckle.Core
httpConfiguration .EnableSwagger(c => c.SingleApiVersion("v1", "A title for your API")) .EnableSwaggerUi();
program.cs
using Microsoft.Owin.Hosting; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OwinTest { class Program { static void Main(string[] args) { StartOptions options = new StartOptions(); options.Urls.Add("http://localhost:9095"); options.Urls.Add("http://127.0.0.1:9095"); options.Urls.Add(string.Format("http://{0}:9095", Environment.MachineName)); using (WebApp.Start<Startup>(options)) { Console.WriteLine("server started..."); Console.ReadLine(); } } } }
6、管理员运行控制器,浏览http://localhost:9095/swagger