.NET
Web Api
▌背景
如何利用OWIN HttpListener server 建立一個Self-host Web Api的應用程式。
|
▌實作
▋加入OWIN套件
|
l 在專案中加入一個RouteConfig.cs 來設定Web Api的路由規則。
public class RouteConfig
{
/// <summary>
/// Configuration
/// </summary>
/// <param
name="appBuilder"></param>
/// <remarks>注意方法名稱必須為Configuration</remarks>
public void Configuration(IAppBuilder appBuilder)
{
HttpConfiguration config = new HttpConfiguration();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
appBuilder.UseWebApi(config);
}
}
|
▋加入ApiController
l 在專案中加入新的Controller,並繼承ApiController
public class TodoController:ApiController
{
[HttpGet]
public IEnumerable<Todo> Get()
{
var todo1 = new Todo() { MyName = "JB", MyAction = "Buy
lunch",
IsFinish = false };
var todo2 = new Todo() { MyName = "JB", MyAction = "Eat
lunch",
IsFinish = false };
var todo3 = new Todo() { MyName = "JB", MyAction = "Sleep", IsFinish = false };
List<Todo> todoList = new List<Todo>();
todoList.Add(todo1);
todoList.Add(todo2);
todoList.Add(todo3);
return todoList.AsEnumerable();
}
[HttpPost]
public void Print(IEnumerable<Todo> todoList)
{
Parallel.ForEach(todoList, todo => {
Console.WriteLine(String.Format("{0} : {1} ({2})", todo.MyName,
todo.MyAction, todo.IsFinish));
});
}
}
|
l DTO 物件定義
public class Todo
{
public String MyName { get; set; }
public String MyAction { get; set; }
public bool IsFinish { get; set; }
}
|
▋主程式加入啟動服務的程式碼
static void Main(string[] args)
{
string baseAddress = "http://localhost:7531/"; //Assaign a port
number here
// Start OWIN host
WebApp.Start<RouteConfig>(url: baseAddress);
#region Self-test : Create HttpCient
and make a request
var client = new HttpClient();
var response =
client.GetAsync(baseAddress + "api/todo/Get").Result;
Console.WriteLine(response);
Console.WriteLine(response.Content.ReadAsStringAsync().Result);
#endregion
Console.ReadLine();
}
|
▋測試
備註:
並在註冊RouteConfig時加入以下程式碼:
public class RouteConfig
{
public void Configuration(IAppBuilder appBuilder)
{
//Skip …
//Enable CORS
config.EnableCors();
}
}
|
[EnableCors(origins: "*", headers: "*", methods: "*")]
|
▌Reference
沒有留言:
張貼留言