๐ฉโ๐ป .NET Framework Self Host
Self Hostโ
ๅฏไปฅๅจ .NET Framework ไธญไธ้ ้้
IIS
๏ผ็ดๆฅๅๅ REST API
ๅปบๆงๆญฅ้ฉโ
ๅปบ็ซๅฐๆกโ
ๅปบ็ซไธๅ Console App (.NET Framework) ็ๅฐๆก
ๅฎ่ฃ SelfHostโ
Install-Package Microsoft.AspNet.WebApi.SelfHost -Version 5.3.0
ๅๅ่จญๅฎโ
- ๆชๆก: Program.cs
internal class Program
{
static void Main(string[] args)
{
// ๆๅฎ่่ฝ็URL
string host = "localhost", port = "8080";
string hostPort = $@"http://{host}:{port}";
var config = new HttpSelfHostConfiguration(hostPort);
// ่จญๅฎ่ทฏ็ฑ
config.Routes.MapHttpRoute("API", "{controller}/{action}/{id}",
new { id = RouteParameter.Optional });
// ๅ็จ Cors
// config.EnableCors();
// ็งป้ค XML ๆ ผๅผ
config.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
// ไฝฟ็จ Json ๆ ผๅผ
config.Formatters.JsonFormatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
// ๅๅๆๅ
Task.Factory.StartNew(async () =>
{
try
{
using (var httpServer = new HttpSelfHostServer(config))
{
httpServer.OpenAsync().Wait(); // ้็ญๅฐ Open ไนๅพๆ่ฝ้ฒ่กๅ
ถไปไบ้
Console.WriteLine("Web API host started...");
//่ผธๅ
ฅexit ๆ Enter ็ตๆ httpServer
string line = null;
do
{
line = Console.ReadLine();
}
while (line != "exit");
Console.WriteLine("Web API host closed...");
//็ตๆ้ฃ็ท
await httpServer.CloseAsync();
}
}
catch (Exception ex)
{
Console.WriteLine($"Web API host error={ex}");
}
});
}
}
Controllerโ
- ๆชๆก: Controllers/TestController.cs
public class TestController : ApiController
{
[HttpGet]
public async Task<IHttpActionResult> Get()
{
await Task.Delay(100);
return Ok("Hi Hi");
}
}
ๅๅโ
ไฝฟ็จ็่ฆฝๅจ่ผธๅ ฅ
http://localhost:port
็ซ้ข้กฏ็คบ็ตๆ
Hi Hi