C# 关于使用newlife包将webapi接口寄宿于一个控制台程序、winform程序、wpf程序运行

C# 关于使用newlife包将webapi接口寄宿于一个控制台程序、winform程序、wpf程序运行

  1. 安装newlife包
    C# 关于使用newlife包将webapi接口寄宿于一个控制台程序、winform程序、wpf程序运行_第1张图片

  2. Program的Main()函数源码

using ConsoleApp3;
using NewLife.Log;

var server = new NewLife.Http.HttpServer
{
    Port = 8080,
    Log = XTrace.Log,
    SessionLog = XTrace.Log
};
server.Map("/", () => "

Hello NewLife!


"
+ DateTime.Now.ToFullString() + "
"
); 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();
  1. MyController 源码
/// 
/// 控制器
/// 
public class MyController
{
    //IHttpActionResult
    /// 
    /// 
    /// 
    /// 
    /// 
    /// 请求路径:http://localhost:8080/api/GetRobotStatus?Code='code'&Name='Name'
    /// 
    [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!";
        }
    }

    /// 
    /// 
    /// 
    /// 请求路径:http://localhost:8080/api/GetRobotStatusJK
    /// 
    [HttpGet]
    public string GetRobotStatusJK()
    {
        try
        {
            var robotModel = new { RobotCode = "RobotCode", RobotName = "RobotName", RobotDesc = "RobotDesc", RobotRemark = "RobotRemark" };
            return "Successful!";
        }
        catch(Exception ex)
        {
            return "Exception!";
        }
        
    }
}
  1. MyHttpHandler 源码
 public class MyHttpHandler : IHttpHandler
    {
        /// 
        /// 
        /// 
        /// 请求路径:http://localhost:8080/myHttpHandler?name=Stone
        /// 
        public void ProcessRequest(IHttpContext context)
        {
            var name = context.Parameters["name"];
            var html = $"

你好,{name}

"
; context.Response.SetResult(html); } }
  1. 源代码百度链接
    链接:https://pan.baidu.com/s/15OxTDOBO_y5bFyrzPW3XPw?pwd=sr3c
    提取码:sr3c

你可能感兴趣的:(c#,wpf,开发语言)