在实际的项目开发中,可能会有在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
欢迎转载,转载请注明:转载自[ http://www.cnblogs.com/zjfree/ ]
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步