C#桌面程序 winform 集成内置WebApi C# 创建HTTP Web API服务,winform项目创建HTTP WEB服务,不使用IIS业务 C#桌面程序WebApi C#winform集
时间:2024-04-05 15:00:36 来源:网络cs 作者:往北 栏目:卖家故事 阅读:
阅读本书更多章节>>>>
C#桌面程序 winform 集成内置WebApi服务
在维护旧的项目时,有时需要提供APP连接的需求,就要提供HTTP服务,winform项目就要提供HTTP服务,就不用再去写个c# web的IIS相关的业务了,简化项目的复杂度。
最新资料下载------> 源代码资料
static void Main() { if (webAPI != null && webAPI.IsListening) { Console.WriteLine("服务已启动..."); return; } else { webAPI = new Webserver("0.0.0.0", 8080, httpServerAPI.DefaultRoute); webAPI.Settings.Headers.Host = "http://0.0.0.0:8080"; webAPI.Events.ServerStarted += httpServerAPI.ServerStarted; webAPI.Events.ServerStopped += httpServerAPI.ServerStopped; webAPI.Events.ServerDisposing += httpServerAPI.ServerDisposing; webAPI.Events.Logger = httpServerAPI.ServerLogger; webAPI.Settings.Debug.Responses = true; webAPI.Settings.Debug.Routing = true; } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); }
public static async Task DefaultRoute(HttpContext ctx) { try { byte[] reqData = ctx.Request.DataAsBytes; if (ctx.Request.Url.WithoutQuery.Equals("/")) { string resp = "<html>" + " <head><title>webAPI</title></head>" + " <body><h2>webAPI</h2><p>webAPI is running!</p></body>" + "</html>"; ctx.Response.StatusCode = 200; ctx.Response.ContentType = "text/html"; await ctx.Response.SendAsync(resp); return; } else { ctx.Response.StatusCode = 404; ctx.Response.ContentType = "text/plain"; ctx.Response.Send(true); return; } } catch (Exception e) { ctx.Response.StatusCode = 500; ctx.Response.ContentType = "text/plain"; ctx.Response.Send(e.ToString()); Console.WriteLine(e.ToString()); return; } }
[StaticRoute(HttpMethod.GET, "/api/GetServerTime")] public static async Task GetServerTime(HttpContext ctx) { ctx.Response.StatusCode = 200; ctx.Response.ContentType = "text/plain"; await ctx.Response.SendAsync(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); return; }
[ParameterRoute(HttpMethod.POST, "/api/Login")] public static async Task UserLogin(HttpContext ctx) { ctx.Response.StatusCode = 200; Console.WriteLine(Encoding.UTF8.GetString(ctx.Request.DataAsBytes)); string json = Encoding.UTF8.GetString(ctx.Request.DataAsBytes); ctx.Response.ContentType = "application/json;charset=UTF-8"; await ctx.Response.SendAsync("{\"code\":OK,\"msg\":\"登陆成功\"}"); return; }
[ParameterRoute(HttpMethod.GET, "/api/GetList/{id}")] public static async Task MyParameterRoute(HttpContext ctx) { ctx.Response.StatusCode = 200; ctx.Response.ContentType = "application/json"; await ctx.Response.SendAsync("{\"code\":1000,\"msg\":\"传入的ID为{" + ctx.Request.Url.Parameters["id"] + "}\"}"); return; }
本文链接:https://www.kjpai.cn/gushi/2024-04-05/154462.html,文章来源:网络cs,作者:往北,版权归作者所有,如需转载请注明来源和作者,否则将追究法律责任!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。