博客园  :: 首页  :: 新随笔  :: 订阅 订阅  :: 管理

C# WinForm基于owin创建WebApi

Posted on 2024-03-05 15:48  PHP-张工  阅读(529)  评论(0编辑  收藏  举报

在实际的项目开发中,可能会有在WinForm程序中提供Web服务器的需求。
通过owin可以很方便的实现,并且可提供Web静态文件访问服务。

操作方法:

1. 在NuGet引用owin

Microsoft.AspNet.WebApi.Owin
Microsoft.AspNet.WebApi.OwinSelfHost
Microsoft.Owin.StaticFiles
2. 添加服务启动配置类 Startup

namespace WebServer
{
    public class Startup
    {
        public void Configuration(IAppBuilder appBuilder)
        {
            // 创建 Web API 的配置
            var config = new HttpConfiguration();
            // 启用标记路由
            config.MapHttpAttributeRoutes();
            // 默认的 Web API 路由
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );


            var physicalFileSystem = new PhysicalFileSystem(@".\Web"); //静态网站根目录
            var options = new FileServerOptions
            {
                EnableDefaultFiles = true,
                FileSystem = physicalFileSystem
            };
            options.StaticFileOptions.FileSystem = physicalFileSystem;
            options.StaticFileOptions.ServeUnknownFileTypes = true;
            options.StaticFileOptions.DefaultContentType = "text/plain";
            options.DefaultFilesOptions.DefaultFileNames = new[] { "Index.html" }; //默认页面(填写与静态网站根目录的相对路径)
            appBuilder.UseFileServer(options);

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

3. 添加 Controllers 目录,创建 QueryController Web服务类

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

namespace WebServer.Controllers
{
    public class QueryController : ApiController
    {
        //// GET api
        //[HttpGet]
        //public IHttpActionResult Json(string id)
        //{
        //    return Json($"hello123:{id}");
        //}

        // GET api
        public string Get(string id)
        {
            return "hello:" + 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)
        {
        }
    }
}

4. 在程序中调用如下代码启动Web服务

// 打开Web服务
var server = WebApp.Start<Startup>(url: "http://localhost:9099/");

// 停止Web服务
server.Dispose();
server = null;

5. 在生成的文件目录,创建Web文件夹,放入静态Web资源(index.html)

6. 访问Web资源
浏览器访问静态资源 http://localhost:9099/ 
浏览器访问WebApi  http://localhost:9099/api/Query/123