Skip to main content

๐Ÿ‘ฉโ€๐Ÿ’ป .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


Refโ€‹