?在維護(hù)舊的項目時,有時需要提供APP連接的需求,就要提供HTTP服務(wù),winform項目就要提供HTTP服務(wù),就不用再去寫個c# web的IIS相關(guān)的業(yè)務(wù)了,簡化項目的復(fù)雜度。只需要簡單化實例就可以實現(xiàn)提供HTTP服務(wù)
static void Main()
{
if (webAPI != null && webAPI.IsListening)
{
Console.WriteLine("服務(wù)已啟動...");
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;
}
文章來源:http://www.zghlxwxcb.cn/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;
}
文章來源地址http://www.zghlxwxcb.cn/news/detail-714680.html
到了這里,關(guān)于C#桌面程序 winform 集成內(nèi)置WebApi C# 創(chuàng)建HTTP Web API服務(wù),winform項目創(chuàng)建HTTP WEB服務(wù),不使用IIS業(yè)務(wù) C#桌面程序WebApi C#winform集的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!