Working console program:
static voidMain(string[] args)
{
// Set up server configuration
HttpSelfHostConfiguration config =newHttpSelfHostConfiguration("http://localhost:8080");
//Route Catches the GET PUT DELETE typical REST based interactions (add more if needed)
config.Routes.MapHttpRoute("API Default","api/{controller}/{id}",new{ id =RouteParameter.Optional},new{ httpMethod =newHttpMethodConstraint(HttpMethod.Get,HttpMethod.Put,HttpMethod.Delete)});
//This allows POSTs to the RPC Style methods http://api/controller/action
config.Routes.MapHttpRoute("API RPC Style","api/{controller}/{action}",new{ httpMethod =newHttpMethodConstraint(HttpMethod.Post)});
//Finally this allows POST to typeical REST post address http://api/controller/
config.Routes.MapHttpRoute("API Default 2","api/{controller}/{action}",new{ action ="Post"},new{ httpMethod =newHttpMethodConstraint(HttpMethod.Post)});
using(HttpSelfHostServer server =newHttpSelfHostServer(config))
{
server.OpenAsync().Wait();Console.WriteLine("Press Enter to quit.");Console.ReadLine();
}
}
Working Controller
public class TaskInstanceQueueController:ApiController
{
publicvoidGet(string id)
{
// Do something with my taskInstanceConsole.WriteLine("Method entered!"+ id);}[ActionName("Post")][HttpPost]publicvoidPost(TaskInstance taskInstance){// Do something with my taskInstanceConsole.WriteLine("REST Post Method entered!");}[ActionName("Queue")][HttpPost]publicvoidQueue(TaskInstance taskInstance){// Do something with my taskInstanceConsole.WriteLine("Queue Method entered!");}[ActionName("Another")][HttpPost]publicvoidAnother(TaskInstance taskInstance){Console.WriteLine("Another Method entered!");}}
RESTful API 实现与控制器设计
本文详细介绍了如何使用 C# 构建 RESTful API,包括设置服务器配置、定义路由以及实现控制器方法来处理 GET、PUT、DELETE 和 POST 请求。
1639

被折叠的 条评论
为什么被折叠?



