在维护旧的项目时,有时需要提供APP连接的需求,就要提供HTTP服务,winform项目就要提供HTTP服务,就不用再去写个c# web的IIS相关的业务了,简化项目的复杂度。只需要简单化实例就可以实现提供HTTP服务
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;
}
文章来源:https://www.toymoban.com/news/detail-714680.html
[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.toymoban.com/news/detail-714680.html
到了这里,关于C#桌面程序 winform 集成内置WebApi C# 创建HTTP Web API服务,winform项目创建HTTP WEB服务,不使用IIS业务 C#桌面程序WebApi C#winform集的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!