首页 > 其他分享 >使用WPF、OwinSelfHost和Swagger创建自托管的Web API

使用WPF、OwinSelfHost和Swagger创建自托管的Web API

时间:2023-06-01 15:12:48浏览次数:58  
标签:Web string OwinSelfHost System API using new config public

在本篇博客中,我将介绍如何在WPF应用程序中使用OwinSelfHost和Swagger来创建自托管的Web API。我们将使用WPF作为我们的应用程序界面,OwinSelfHost来自托管我们的Web API,并使用Swagger来为我们的API生成文档。

首先,确保你的计算机上已安装了以下组件:

  • Visual Studio2017
  • .NET Framework(至少需要4.5版本)

接下来,按照以下步骤进行操作:

步骤1:创建新的WPF项目 在Visual Studio中创建一个新的WPF项目。命名它为"SwaggerBlog"。

步骤2:安装必要的NuGet包 在解决方案资源管理器中,右键单击项目名称,选择"管理NuGet程序包"。然后,按照以下步骤安装所需的包:

  • Microsoft.AspNet.WebApi.OwinSelfHost
  • Microsoft.Owin.Cors
  • Swashbuckle
  • .。。。。

步骤3:创建API控制器 在解决方案资源管理器中,右键单击"Controllers"文件夹,选择"添加" -> "类"。命名为"模拟接口Controller.cs"。在类中添加以下代码:

using Newtonsoft.Json.Linq;
using System.Threading.Tasks;
using System.Web.Http;

namespace MockAPI.Controllers
{
    /// <summary>
    /// 模拟接口
    /// </summary>
    [RoutePrefix("api")]
    public class 模拟接口Controller : BaseController
    {
        /// <summary>
        /// 同步信息
        /// </summary>
        /// <returns></returns>
        [Route("fs_syncPayinfo")]
        [HttpGet]
        public IHttpActionResult SyncPayInfo()
        {
            string json = @"{""code"":1,""message"":""同步成功""}";
            return Json(JObject.Parse(json));
        }
}

步骤4:配置Swagger 在解决方案资源管理器中,右键单击"Properties"文件夹,选择"添加" -> "新建文件"。命名为"Startup.cs"。在文件中添加以下代码:

其中包含了记录日志中间件等类,具体看下载的代码

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web.Http;
using System.Web.Http.Filters;
using System.Xml;
using Microsoft.Owin;
using Microsoft.Owin.Cors;
using MockAPI.Common;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Owin;
using Swashbuckle.Application;
using Swashbuckle.Swagger;

[assembly: OwinStartup(typeof(MockAPI.Startup))]

namespace MockAPI
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            HttpConfiguration config = new HttpConfiguration();

            JsonSerializerSettings setting = new JsonSerializerSettings()
            {
                //日期类型默认格式化处理
                DateFormatHandling = DateFormatHandling.MicrosoftDateFormat,
                DateFormatString = "yyyy-MM-dd HH:mm:ss",
                //驼峰样式
                ContractResolver = new CamelCasePropertyNamesContractResolver(),
                //空值处理
                //NullValueHandling = NullValueHandling.Ignore,
                //设置序列化的最大层数
                MaxDepth = 10,
                //解决json序列化时的循环引用问题
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore
            };
            config.Formatters.JsonFormatter.SerializerSettings = setting;
            config.Formatters.Remove(config.Formatters.XmlFormatter);

            config.Filters.Add(new HandlerErrorAttribute());
            //config.Routes.MapHttpRoute(
            //    name: "DefaultApi",
            //    routeTemplate: "api/{controller}/{action}/{id}",
            //    defaults: new
            //    {
            //        id = RouteParameter.Optional
            //    }
            //);
            ConfigureSwagger(config);
            //添加路由路径
            config.MapHttpAttributeRoutes();
            app.UseCors(CorsOptions.AllowAll);

            app.Use<LoggingMiddleware>();
            app.UseWebApi(config);

        }
        private static void ConfigureSwagger(HttpConfiguration config)
        {
            var thisAssembly = typeof(Startup).Assembly;
            config.EnableSwagger(c =>
             {
                 c.SingleApiVersion("v1", "MockAPI");

                    //设置接口描述xml路径地址
                    var webApiXmlPath = string.Format(string.Format("{0}/MockAPI.xml", AppDomain.CurrentDomain.BaseDirectory));

                 c.IncludeXmlComments(webApiXmlPath);
                 c.UseFullTypeNameInSchemaIds();
                    //加入控制器描述
                    c.CustomProvider((defaultProvider) => new SwaggerControllerDescProvider(defaultProvider, webApiXmlPath));
             })
             .EnableSwaggerUi(c =>
             {
                 c.DocumentTitle("MockAPI");
                 c.InjectJavaScript(thisAssembly, "MockAPI.Common.Swagger.js");
             });
        }

        public class HandlerErrorAttribute : ExceptionFilterAttribute
        {
            /// <summary>
            /// 控制器方法中出现异常,会调用该方法捕获异常
            /// </summary>
            /// <param name="context">提供使用</param>
            public override void OnException(HttpActionExecutedContext context)
            {
                base.OnException(context);
                LogFile.WriteError(context.Exception.Message);
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new StringContent(
                   JsonConvert.SerializeObject(
                    new
                    {
                        code = -1,
                        data = "xxx",
                        msg = context.Exception.Message
                    }), Encoding.UTF8, "text/json")
                });
            }
        };

        public class SwaggerControllerDescProvider : ISwaggerProvider
        {
            private readonly ISwaggerProvider _swaggerProvider;
            private static ConcurrentDictionary<string, SwaggerDocument> _cache = new ConcurrentDictionary<string, SwaggerDocument>();
            private readonly string _xml;
            /// <summary>
            /// 
            /// </summary>
            /// <param name="swaggerProvider"></param>
            /// <param name="xml">xml文档路径</param>
            public SwaggerControllerDescProvider(ISwaggerProvider swaggerProvider, string xml)
            {
                _swaggerProvider = swaggerProvider;
                _xml = xml;
            }

            public SwaggerDocument GetSwagger(string rootUrl, string apiVersion)
            {

                var cacheKey = string.Format("{0}_{1}", rootUrl, apiVersion);
                SwaggerDocument srcDoc = null;
                //只读取一次
                if (!_cache.TryGetValue(cacheKey, out srcDoc))
                {
                    srcDoc = _swaggerProvider.GetSwagger(rootUrl, apiVersion);

                    srcDoc.vendorExtensions = new Dictionary<string, object> { { "ControllerDesc", GetControllerDesc() } };
                    _cache.TryAdd(cacheKey, srcDoc);
                }
                return srcDoc;
            }

            /// <summary>
            /// 从API文档中读取控制器描述
            /// </summary>
            /// <returns>所有控制器描述</returns>
            public ConcurrentDictionary<string, string> GetControllerDesc()
            {
                string xmlpath = _xml;
                ConcurrentDictionary<string, string> controllerDescDict = new ConcurrentDictionary<string, string>();
                if (File.Exists(xmlpath))
                {
                    XmlDocument xmldoc = new XmlDocument();
                    xmldoc.Load(xmlpath);
                    string type = string.Empty, path = string.Empty, controllerName = string.Empty;

                    string[] arrPath;
                    int length = -1, cCount = "Controller".Length;
                    XmlNode summaryNode = null;
                    foreach (XmlNode node in xmldoc.SelectNodes("//member"))
                    {
                        type = node.Attributes["name"].Value;
                        if (type.StartsWith("T:"))
                        {
                            //控制器
                            arrPath = type.Split('.');
                            length = arrPath.Length;
                            controllerName = arrPath[length - 1];
                            if (controllerName.EndsWith("Controller"))
                            {
                                //获取控制器注释
                                summaryNode = node.SelectSingleNode("summary");
                                string key = controllerName.Remove(controllerName.Length - cCount, cCount);
                                if (summaryNode != null && !string.IsNullOrEmpty(summaryNode.InnerText) && !controllerDescDict.ContainsKey(key))
                                {
                                    controllerDescDict.TryAdd(key, summaryNode.InnerText.Trim());
                                }
                            }
                        }
                    }
                }
                return controllerDescDict;
            }
        }
    }
}
View Code

步骤5:配置OwinSelfHost 启动等等 

  private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            setMin();
            wsl = this.WindowState;
            this.Hide();//启动后直接最小化
            this.ResizeMode = ResizeMode.CanMinimize;
            this.txtDevice.Text = DeviceNo;
            this.txtDevice.IsReadOnly = true;

            var registry = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);//检索指定的子项
            if (registry != null)
            {
                object a = registry.GetValue(Path.GetFileName(System.Windows.Forms.Application.ExecutablePath));
                if (a != null) this.cboAuto.IsChecked = true;
                registry.Close();
            }
            this.cboAuto.Checked += BtnClickTurnOn;
            this.cboAuto.Unchecked += BtnClickTurnOff;

            StartOptions options = new StartOptions();
            options.Urls.Add("http://+:8033");
            // 启动 OWIN host
            _disposable = WebApp.Start<Startup>(options);
        }

这里代码只有部分截图,具体下载代码查看   点击下载

 点击API地址打开文档界面

 

 

至此,我们已成功创建了一个使用WPF、OwinSelfHost和Swagger的自托管Web API。你可以根据自己的需求进一步扩展和定制这个应用程序。

标签:Web,string,OwinSelfHost,System,API,using,new,config,public
From: https://www.cnblogs.com/xxxin/p/17449038.html

相关文章

  • Zapier:1.4亿美金ARR的内容营销之道
    一站式SaaS应用管理平台Pandium在2021年调研过当时市值前15大的SaaS公司,其产品对外的API或扩展数量的中位数已经达到了347个。这些大公司(如上图)几乎都建立了生态或应用商店,力推基于API的开放连接。数量最多的是身份管理SaaS平台Okta,超过7,000个应用跟其产品打通。这也不难解释为......
  • python 搭建一个Web自动化测试环境
    搭建一个Web自动化测试环境的具体步骤如下:1.安装Python:首先需要安装Python编程语言。可以从Python官方网站下载最新的稳定版本,并按照安装指南进行安装。官方网站链接:https://www.python.org2.安装浏览器驱动程序(注意:浏览器版本需要和驱动版本对应):根据使用的浏览器类型,下载对应......
  • 有赞 调用 api 接口(有赞开放平台)
    ps:先注册有赞账号有赞https://www.youzan.com/有赞开放平台http://open.youzan.com/有赞开发者后台http://open.youzan.com/developer/app/index接入说明:http://open.youzan.com/docAPI文档:http://open.youzan.com/api***********************************************......
  • web自动化
    元素定位XPATH选择器什么是xpath?XPath即为XML路径语言,它是一种用来(标准通用标记语言的子集)在HTML\XML文档中查找信息的语言。W3School官方文档:http://www.w3school.com.cn/xpath/index.asp什么是XML?XML指可扩展标记语言(EXtensibleMarkupLanguage)XML是一种标记语言,很......
  • WEB漏洞—SQL注入之堆叠及WAF绕过注入
    1、堆叠查询注入stackedinjections(堆叠注入)从名词的含义就可以看到应该是一堆sql语句(多条)一起执行。在sql语句中以; 结束语句mysql>select*fromusers;+----+----------+------------+|id|username|password|+----+----------+------------+|1|Dumb......
  • vues全局使用WebSocket 多次吊起
    //import{showInfoMsg,showErrorMsg}from'@/utils/popInfo'//importElementUIfrom'element-ui';import{Toast}from'vant';functioninitWebSocket(that,baseObj){console.log(baseObj)console.log(this)co......
  • webshell后门中执行交互命令看到的sysmon数据采集和检测
    下载phpstudy,链接:https://public.xp.cn/upgrades/phpStudy_64.zip,如下图启动wnmp。  webshell内容:<?phpecho"Yourresponseis:";?><?php@eval($_GET['cmd']);?>写入C:\phpstudy_pro\WWW下的shell.php文件。 浏览器执行命令:localhost/shell.php?cmd=syste......
  • Go Web
    GoWeb主要介绍Go的net/http包,Gin框架,gRPC。(多复习,多回顾,多输出)参考:Gohttp包详解-简书(jianshu.com)【置顶】Go语言学习之路/Go语言教程|李文周的博客(liwenzhou.com)net/Http包Go语言中的http包提供了创建http服务或者访问http服务所需要的能力,不需要额外......
  • python~Flask框架建立web应用
    通过python来开发web应用,可以产简化了web开发的流程,功能和函数库也是非常丰富,我们也是开箱即用,目前比较流程的WEB框架就是Flask和django。根据2020年JetBrainsPython开发人员调查,Django和Flask是迄今为止最受欢迎的两个PythonWeb框架。考虑到Web开发行业在过去五年左右的时间......
  • 在Eclipse中安装WebLogic12c的步骤
     1.  2.  3.  ......