C# 关于使用newlife包将webapi接口寄宿于一个控制台程序、winform程序、wpf程序运行
-
安装newlife包
-
Program的Main()函数源码
using ConsoleApp3;
using NewLife.Log;
var server = new NewLife.Http.HttpServer
{
Port = 8080,
Log = XTrace.Log,
SessionLog = XTrace.Log
};
server.Map("/", () => "<h1>Hello NewLife!</h1></br> " + DateTime.Now.ToFullString() + "</br><img src=\"logos/leaf.webp\" />");
server.Map("/user", (String act, Int32 uid) => new { code = 0, data = $"User.{act}({uid}) success!" });
server.Map("/myHttpHandler", new MyHttpHandler());
server.MapStaticFiles("/logos", "images/");
server.MapController<MyController>("/api");
server.Start();
Console.ReadLine();
- MyController 源码
/// <summary>
/// 控制器
/// </summary>
public class MyController
{
//IHttpActionResult
/// <summary>
///
/// </summary>
/// <param name="Code"></param>
/// <param name="Name"></param>
/// 请求路径:http://localhost:8080/api/GetRobotStatus?Code='code'&Name='Name'
/// <returns></returns>
[HttpGet]
public string GetRobotStatus(string Code, string Name)
{
try
{
var robotModel = new { RobotCode = "RobotCode", RobotName = "RobotName", RobotDesc = "RobotDesc", RobotRemark = "RobotRemark" };
return "Successful!";
}
catch (Exception ex)
{
return "Exception!";
}
}
/// <summary>
///
/// </summary>
/// 请求路径:http://localhost:8080/api/GetRobotStatusJK
/// <returns></returns>
[HttpGet]
public string GetRobotStatusJK()
{
try
{
var robotModel = new { RobotCode = "RobotCode", RobotName = "RobotName", RobotDesc = "RobotDesc", RobotRemark = "RobotRemark" };
return "Successful!";
}
catch(Exception ex)
{
return "Exception!";
}
}
}
- MyHttpHandler 源码
public class MyHttpHandler : IHttpHandler
{
/// <summary>
///
/// </summary>
/// 请求路径:http://localhost:8080/myHttpHandler?name=Stone
/// <param name="context"></param>
public void ProcessRequest(IHttpContext context)
{
var name = context.Parameters["name"];
var html = $"<h2>你好,<span color=\"red\">{name}</span></h2>";
context.Response.SetResult(html);
}
}
- 源代码百度链接
链接:https://pan.baidu.com/s/15OxTDOBO_y5bFyrzPW3XPw?pwd=sr3c
提取码:sr3c