使用控制台作为ASP.NET webapi的宿主
一、前言
一般情况下,我们在使用ASP.NET WebApi的时候习惯创建一个Web应用程序,最终将程序部署到IIS进行运行。但有时候,我们需要在控制台或者Windows服务中运行webapi程序,这时就不适合使用IIS。这时就可以使用自托管模式。asp.net web api的自托管模式HttpSelfHostServer可以以控制台程序或windows服务程序为宿主,不单单依赖于IIS web服务器
注意:这里使用的是.Net Framework做控制台或者Windows服务
二、示例代码
1、创建控制台程序,项目结构如下
2、安装Microsoft.AspNet.WebApi.SelfHost
通过Nuget安装Microsoft.AspNet.WebApi.SelfHost,注意选择对应的.Net Framework版本
安装完以后会包括如下的DLL
-
System.Web.Http.dll
-
The core runtime assembly for ASP.NET Web API
-
-
System.Net.Http.dll
-
Provides a programming interface for modern HTTP applications. This includes HttpClient for sending requests over HTTP, as well as HttpRequestMessage and HttpResponseMessage for processing HTTP messages
-
-
System.Net.Http.WebRequest.dll
-
Provides additional classes for programming HTTP applications
-
-
System.Web.Http.SelfHost.dll
-
Contains everything you need to host ASP.NET Web API within your own process (outside of IIS)
-
-
System.Net.Http.Formatting.dll
-
Adds support for formatting and content negotiation to System.Net.Http. It includes support for JSON, XML, and form URL encoded data
-
3、创建Routes路由配置类
using System.Net.Http; using System.Web.Http; using System.Web.Http.Routing; using System.Web.Http.SelfHost; namespace WebApiSelfHostDemo { public class Routes { public static void ConfigureRoutes(HttpSelfHostConfiguration config) { config.Routes.MapHttpRoute("DefaultApiWithId", "Api/{controller}/{id}", new { id = RouteParameter.Optional }, new { id = @"\d+" }); config.Routes.MapHttpRoute("DefaultApiWithAction", "Api/{controller}/{action}"); config.Routes.MapHttpRoute("DefaultApiGet", "Api/{controller}", new { action = "Get" }, new { httpMethod = new HttpMethodConstraint(HttpMethod.Get) }); config.Routes.MapHttpRoute("DefaultApiPost", "Api/{controller}", new { action = "Post" }, new { httpMethod = new HttpMethodConstraint(HttpMethod.Post) }); } } }
4、创建RestApiServer类
using System; using System.Web.Http.SelfHost; namespace WebApiSelfHostDemo { public class RestApiServer { public const int PORT = 8091; private static HttpSelfHostServer _server; /// <summary> /// start server to listen http request /// </summary> /// <param name="params"></param> public static void StartUp(string[] @params) { string host = string.Empty; #if DEBUG host = "localhost"; #else host = SelfHostHelper.GetHandlerIP(); #endif try { if (_server != null) { _server.CloseAsync().Wait(); _server.Dispose(); _server = null; } string baseAddress = $"http://{host}:{PORT}"; var config = new HttpSelfHostConfiguration(baseAddress); Console.WriteLine(); Routes.ConfigureRoutes(config); Console.WriteLine("Instantiating The Server..."); _server = new HttpSelfHostServer(config); _server.OpenAsync().Wait(); Console.WriteLine("Server is Running Now and listen : " + baseAddress); } catch (Exception e) { throw e; } } public static void ShutDown() { if (_server != null) { _server.CloseAsync(); _server.Dispose(); } } } }
5、在Main方法中调用
using System; namespace WebApiSelfHostDemo { class Program { static void Main(string[] args) { try { RestApiServer.StartUp(new string[] { }); } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.ReadKey(); } } }
运行结果
6、添加控制器
using System.Web.Http; namespace WebApiSelfHostDemo { public class TestSelfHostController : ApiController { public string Get() { return "Hi!, Self-Hosted Web Api Application Get"; } public string Get(int id) { return $"Hi!, Self-Hosted Web Api Application Get With Id:{id} "; } } }
使用Postman测试
测试带参数
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2020-03-07 ASP.NET Core:依赖注入
2017-03-07 使用C#实现实体类和XML相互转换