Winform搭建简易WebAPI方法


一、Owin使用

1.创建控制台项目
2.NuGet添加Microsoft.AspNet.WebApi.Owin和Microsoft.Aspnet.WebApi.OwinSelfHost
3.添加Startup类


1.1、Startup

Startup是OWIN约定的,用于对OWIN做相关配置,代码如下:

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)
        {
            //创建Web API 的配置
            var config = new HttpConfiguration();
            //启动标记路由
            config.MapHttpAttributeRoutes();
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}/{id}",//{action}目的是为了一个Controller能有多个Get Post方法
                defaults: new { id = RouteParameter.Optional }
            );
       //配置swagger 
            config
                .EnableSwagger(c => c.SingleApiVersion("v1", "接口开发文档"))
                .EnableSwaggerUi();

            //清除xml格式,使用json格式
            config.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
            config.Formatters.Add(new JsonMediaTypeFormatter());

            //将路有配置附加到appBuilder
            appBuilder.UseWebApi(config);
        }
    }
}

 

1.2、Controllers类

新建一个queryController类,代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;

namespace OwinTest{
    public class queryController:ApiController{
        //get api
        public string Get(string id)
        {
            return id;
        }
        // POST api
         public string Post([FromBody] string value)
        {
            return value;
        }
        // PUT api
        public void Put(int id, string value)
        {
        }
        // DELETE api
        public void Delete(int id)
        {
        }
    }
}

自建一个PersonController类,代码如下:接口的命名规则是:接口名+Controller

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Http;

namespance OwinTest{
    public class PersonController:ApiController{
        Person[] personList = new Person[] {
            new Person { Id= 1,Age = 2,Name="DANNY"},
            new Person { Id = 2,Age = 3,Name = "Danny123"},
            new Person { Id =3,Age = 4,Name = "dANNY456"}
        };
        
        [HttpGet]
        [Route("api/person/getAll")]
        public List<Person> GetListAll(){
            return personList.toList();
        }
        
        public List<Person> Get(string id){
            return personList.toList();
        }
    }
}

1.3、启动WebAPI服务

Program代码如下,启动项目: 

using Microsoft.Owin.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace OwinTest
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                //端口号
                string port = "9000";
                //电脑所有ip地址都启用该端口服务
                string baseAddress = "http://localhost:" + port + "/";
                ////指定ip地址启用该端口服务
                //string baseAddress = "http://192.168.0.70:" + port + "/";
                //启动OWIN host 
                IDisposable myOwinServer = WebApp.Start<Startup>(url: baseAddress);
                //打印服务所用端口号
                Console.WriteLine("Http服务端口:" + port);
                //测试结果
                //创建HttpCient测试webapi 
                HttpClient client = new HttpClient();
                //通过get请求数据
                var response = client.GetAsync("http://localhost:" + port + "/api/person/getAll").Result;
                //打印请求结果
                Console.WriteLine(response);
                Console.WriteLine("Http服务初始化成功!");
                Console.ReadLine();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Http服务初始化失败!");
                Console.WriteLine(ex.ToString());
            }
        }

        /// <summary>
        /// 释放资源
        /// </summary>
        /// <param name="myOwinServer"></param>
        public void closeOwin(IDisposable myOwinServer)
        {
            myOwinServer.Dispose();
        }
    }
}

 

Person
public class Person{
    public int Id{set;get;}
    public string Name{get;set;}
    public int Age{set;get;}
}

 2.安装使用SWagger

Install-Package Swashbuckle.Core
//在Startup里面配置swagger
httpConfiguration .EnableSwagger(c => c.SingleApiVersion("v1", "A title for your API")) .EnableSwaggerUi();
进入swagger:浏览http://localhost:9000/swagger

 

 

到此结束搭建

 

 

posted @ 2022-12-08 16:12  宇宙无敌狗蛋  阅读(4291)  评论(0编辑  收藏  举报