为了能够在桌⾯端软件中简单⽅便的对外提供RestApi接⼝,参考Java SpringMVC框架使⽤C#语⾔编写了⼀个简易RestApi服务器框架,⽬前⽀持: - 静态页⾯处理
- GET/POST/PUT/DELETE请求
- ⽀持返回JSON
- ⽀持路由⽅法
- ⽀持⾃定义过滤器
- ⽀持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());
}
}
controller和service上增加Component注解后,服务启动时会进⾏⾃动扫描
class Program
{
static void Main(string[] args)
{
new RestApplicationServer().run();
}
}
⽰例三 增加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注解后,服务启动时会进⾏⾃动扫描