Web Api Self-Host
今天有在研究SignalR, 发现SignalR可以使用Self-Host的方式,就突发奇想,Web Api是不是也可以使用Self-Host的方式寄宿在Console Application或者其他的地方。
微软MSDN上给出的详细的答案,Web Api和WCF以及SignalR一样,支持Self-Host。
创建Self-Host项目
新建Console Application
创建成功之后,使用Nuget引入Web Api和Owin包。
打开Package Manager Console, 在里面录入以下命令
Install-Package Microsoft.AspNet.WebApi.OwinSelfHost
配置Web API Self-Host
在解决方案管理窗口,右键点击项目,选择Add/Class, 添加一个新文件Startup.cs
在Startup.cs中添加Configuration方法,该方法中指定了当前项目启用Web Api并指定了路由规则
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | using Owin; using System.Web.Http; namespace OwinSelfhostSample { public class Startup { // This code configures Web API. The Startup class is specified as a type // parameter in the WebApp.Start method. 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); } } } |
添加 Web Api Controller
在解决方案中,右键点击项目,选择Add/Class, 添加ValuesController.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 | using System.Collections.Generic; using System.Web.Http; namespace OwinSelfhostSample { public class ValuesController : ApiController { // GET api/values public IEnumerable< string > Get() { return new string [] { "value1" , "value2" }; } // GET api/values/5 public string Get( int id) { return "value" ; } // POST api/values public void Post([FromBody] string value) { } // PUT api/values/5 public void Put( int id, [FromBody] string value) { } // DELETE api/values/5 public void Delete( int id) { } } } |
使用Owin Host
修改Program.cs, 定义web api的base url, 并启动Owin Host
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | using Microsoft.Owin.Hosting; using System; namespace SelfHost { class Program { static void Main( string [] args) { string baseAddress = "http://localhost:9000/" ; // Start OWIN host using (WebApp.Start<Startup>(url: baseAddress)) { Console.WriteLine( "App Server started." ); Console.ReadLine(); } } } } |
使用Postman测试Api
启动解决方案,等待程序显示”App Server Started.”
打开Postman输入测试的Api Url, 即得到正确的结果。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?