C# 关于使用newlife包将webapi接口寄宿于一个控制台程序、winform程序、wpf程序运行
-
安装newlife包
文章来源:https://www.toymoban.com/news/detail-615619.html -
Program的Main()函数源码文章来源地址https://www.toymoban.com/news/detail-615619.html
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
到了这里,关于C# 关于使用newlife包将webapi接口寄宿于一个控制台程序、winform程序、wpf程序运行的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!