windows service承载的web api宿主搭建(Microsoft.Owin+service)

今天突然想起改良一下以前搭建的“windows service承载的web api”服务,以前也是直接引用的类库,没有使用nuget包,时隔几年应该很旧版本了吧。所以本次把需要nuget获取的包记录一下。

1

2

3

4

5

6

7

8

9

10

11

12

<?xml version="1.0" encoding="utf-8"?>

<packages>

  <package id="log4net" version="2.0.8" targetFramework="net461" />

  <package id="Microsoft.AspNet.WebApi.Client" version="5.2.7" targetFramework="net461" />

  <package id="Microsoft.AspNet.WebApi.Core" version="5.2.7" targetFramework="net461" />

  <package id="Microsoft.AspNet.WebApi.Owin" version="5.2.7" targetFramework="net461" />

  <package id="Microsoft.Owin" version="4.0.0" targetFramework="net461" />

  <package id="Microsoft.Owin.Host.SystemWeb" version="4.0.0" targetFramework="net461" />

  <package id="Microsoft.Owin.Hosting" version="4.0.0" targetFramework="net461" />

  <package id="Newtonsoft.Json" version="12.0.1" targetFramework="net461" />

  <package id="Owin" version="1.0" targetFramework="net461" />

</packages>

 

还有几点需要注意一下:

1、设定webapi仅仅使用json格式

复制代码

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;

namespace NetMiddlewareSvr
{
    /// <summary>
    /// Json格式头部类
    /// </summary>
    public class JsonContentNegotiator : IContentNegotiator
    {
        private readonly JsonMediaTypeFormatter _jsonFormatter;

        public JsonContentNegotiator(JsonMediaTypeFormatter formatter)
        {
            _jsonFormatter = formatter;
        }

        public ContentNegotiationResult Negotiate(Type type, HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters)
        {
            var result = new ContentNegotiationResult(_jsonFormatter, new MediaTypeHeaderValue("application/json"));
            return result;
        }
    }
}

复制代码

2、修改默认路由规则:

复制代码

using Owin;
using System.Net.Http.Formatting;
using System.Web.Http;

namespace NetMiddlewareSvr
{
    public class RegisterRoutesStartup
    {
        public void Configuration(IAppBuilder appBuilder)
        {
            HttpConfiguration config = new HttpConfiguration();
            //自定义路由
            config.Routes.MapHttpRoute(
              name: "CustomApi",
              routeTemplate: "api/{controller}/{action}/{id}",
              defaults: new { id = RouteParameter.Optional }
            );
            //只响应Json请求
            var jsonFormatter = new JsonMediaTypeFormatter();
            config.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter));
            appBuilder.UseWebApi(config);
        }
    }
}

复制代码

3、启动监听

复制代码

 public partial class NetMiddwareService : ServiceBase
    {
        private IDisposable hostObject;
        public NetMiddwareService()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            hostObject = hostObject = WebApp.Start<RegisterRoutesStartup>("http://" + "127.0.0.1" + ":5990");
        }

        protected override void OnStop()
        {
        }
    }

复制代码

 补充一下nuget的顺序:Microsoft.Owin->Microsoft.Owin.Hosting->Microsoft.AspNet.WebApi.Core,剩下的是依赖包自动导入的。当然log4net和Newtonsoft.Json不是owin的依赖包

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
是的,WinForm 可以通过 OWIN 框架实现 WebAPI 的开发。OWIN 是 Open Web Interface for .NET 的缩写,是一个开放式标准,允许 .NET 应用程序通过中间件来处理 HTTP 请求和响应。 具体实现步骤如下: 1. 安装 Microsoft.AspNet.WebApi.OwinSelfHost NuGet 包。 2. 创建 WebAPI 控制器。 3. 在 Program.cs 文件中,编写以下代码以启动 WebAPI: ``` using Microsoft.Owin.Hosting; using System; namespace MyWebAPI { static class Program { static void Main(string[] args) { string baseAddress = "http://localhost:9000/"; // Start OWIN host using (WebApp.Start<Startup>(url: baseAddress)) { Console.WriteLine("WebAPI started at " + baseAddress); Console.ReadLine(); } } } } ``` 4. 创建 Startup.cs 文件,并编写以下代码: ``` using System.Web.Http; using Microsoft.Owin; using Owin; [assembly: OwinStartup(typeof(MyWebAPI.Startup))] namespace MyWebAPI { public class Startup { public void Configuration(IAppBuilder appBuilder) { // Configure Web API for self-host. HttpConfiguration config = new HttpConfiguration(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); appBuilder.UseWebApi(config); } } } ``` 以上代码会将 WebAPI 的路由配置到 /api/{controller}/{id} 上。 5. 最后,在 WinForm 窗体中创建 HttpClient 对象,并使用它来调用 WebAPI: ``` using (var client = new HttpClient()) { client.BaseAddress = new Uri("http://localhost:9000/"); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // HTTP GET HttpResponseMessage response = await client.GetAsync("api/products/1"); if (response.IsSuccessStatusCode) { Product product = await response.Content.ReadAsAsync<Product>(); Console.WriteLine("{0}\t${1}\t{2}", product.Name, product.Price, product.Category); } } ``` 以上就是通过 OWIN 实现 WinForm 中 WebAPI 的简单过程。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

afeng124

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值