使用C#快速搭建Rest服务

使⽤C#快速搭建Rest服务
为了能够在桌⾯端软件中简单⽅便的对外提供RestApi接⼝,参考Java SpringMVC框架使⽤C#语⾔编写了⼀个简易RestApi服务器框架,⽬前⽀持:
- 静态页⾯处理
- GET/POST/PUT/DELETE请求
- ⽀持返回JSON
- ⽀持路由⽅法
- ⽀持⾃定义过滤器
- 服务器返回数据⽀持gzip压缩
- ⽀持Component变量⾃动注⼊
- ⽀持Component⾃动扫描
- GET/POST⽀持查询参数,POST⽀持body数据
- 注解⽀持
- Component
- WebFilter
- RequestMapping
- Autowired
- RequestBody
- RequestParam
快速开始
⽰例⼀ 静态页⾯映射
new RestApplicationServer().run(new RestConfiguration {
StaticFileConfigurations = new List<StaticFileConfiguration>() {
new StaticFileConfiguration("/e", "E:\\"),
new StaticFileConfiguration("/f", "F:\\")
}
});
⽰例⼆ ⾃定义路由
1.添加Controller
[Component("PersonController")]
public class PersonController
{
[Autowired]
public PersonService personService;
private ILogger logger = LoggerFactory.GetLogger();        [RequestMapping("GET","/api/person/list")]
public List<Person> GetPersonList()
{
return personService.GetPersonList();
}
[RequestMapping("GET", "/api/person")]
public Person GetPerson([RequestParam("id")]int id)        {
logger.Debug("id:"+id);
return personService.GetPerson((int)id);
}
[RequestMapping("POST", "/api/person")]
public string Create([RequestBody] Person person)        {
logger.Info("person:" + person.ToString());
return "ok";
}
}
2.添加Service
[Component("PersonService")]
public class PersonService
{
private ILogger logger = new ConsoleLogger();
public List<Person> GetPersonList() {
return TestData.PersonList;
}
public Person GetPerson(int id)
{
return TestData.PersonList.Find(x => x.id == id);
}
public void Create(Person person)
{
logger.Debug(person.ToString());
}
}
3.启动服务
controller和service上增加Component注解后,服务启动时会进⾏⾃动扫描
class Program
{
static void Main(string[] args)
{
new RestApplicationServer().run();
}
}
⽰例三 增加Filter
1. 添加⼀个计算接⼝处理耗时的filter
[WebFilter(1, "/")]
public class StopWacthFilter : IFilter
{
public void Filter(HttpRequest request,ref HttpResponse response, ProcessChain chain, int nextIndex)        {
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
chain.doFilter(request,ref response, nextIndex);
stopwatch.Stop();
简易过滤器Console.WriteLine(request.Method + " "+request.Path+ ", 耗时:"+(stopwatch.ElapsedMilliseconds).ToString()+"ms");        }
}
⾃定义filter上增加WebFilter注解后,服务启动时会进⾏⾃动扫描

本文发布于:2024-09-23 01:39:21,感谢您对本站的认可!

本文链接:https://www.17tex.com/tex/4/350811.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:服务   框架   数据   启动   计算
留言与评论(共有 0 条评论)
   
验证码:
Copyright ©2019-2024 Comsenz Inc.Powered by © 易纺专利技术学习网 豫ICP备2022007602号 豫公网安备41160202000603 站长QQ:729038198 关于我们 投诉建议