ASP.NET Web API Self-Host 환경에서 클라이언트 IP 주소 가져오기

ASP.NET Web API Self-Host 프로젝트에서는 OWIN Self-Host와는 다른 방식으로 클라이언트 IP 주소를 얻을 수 있습니다. 주요 방법은 다음과 같습니다:

  • Request.Properties["System.ServiceModel.Channels.RemoteEndpointMessageProperty"].Address 속성을 활용합니다.

Self-Host 프로젝트 설정 개요 Self-Host 프로젝트를 구성하는 일반적인 단계는 다음과 같습니다:

  1. Windows Forms 애플리케이션(.NET Framework) 프로젝트를 생성하고 이름을 'SelfHostSample'으로 지정합니다.
  2. 기본 폼인 Form1의 이름을 MainForm으로 변경합니다.
  3. NuGet 패키지 관리자를 통해 Microsoft.AspNet.WebApi.SelfHost 패키지를 설치합니다 (OWIN Self-Host가 아닌 것을 확인하세요).
  4. MainController라는 이름의 API 컨트롤러 클래스를 추가합니다.

필수 참조 프로젝트에 다음 네임스페이스에 대한 참조가 추가되어야 합니다:

  • System.ServiceModel
  • System.Web

코드 예시

Program.cs

using System;
using System.Windows.Forms;

namespace SelfHostSample
{
    internal static class Program
    {
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MainForm());
        }
    }
}

MainController.cs 이 컨트롤러는 클라이언트의 IP 주소를 조회하는 엔드포인트 역할을 합니다. 두 가지 일반적인 방법을 사용하여 IP 주소를 추출하려고 시도합니다.

using System.ServiceModel.Channels;
using System.Web;
using System.Web.Http;

namespace SelfHostSample
{
    public class MainController : ApiController
    {
        [HttpGet, HttpPost]
        public IHttpActionResult GetClientIpAddress()
        {
            string clientIp = string.Empty;

            // MS_HttpContext 속성을 사용하여 IP 주소 가져오기 시도
            if (base.Request.Properties.TryGetValue("MS_HttpContext", out object httpContextWrapper))
            {
                clientIp = ((HttpContextWrapper)httpContextWrapper).Request.UserHostAddress;
            }

            // RemoteEndpointMessageProperty 속성을 사용하여 IP 주소 가져오기 시도
            if (base.Request.Properties.TryGetValue(RemoteEndpointMessageProperty.Name, out object remoteEndpointProperty))
            {
                clientIp = ((RemoteEndpointMessageProperty)remoteEndpointProperty).Address;
            }

            return Ok(clientIp);
        }
    }
}

MainForm.cs 이 폼은 Web API 호스트를 시작하는 버튼을 제공합니다. 버튼 클릭 시 HTTP 리스너를 설정하고 서버를 시작합니다.

using System;
using System.Net.Http.Formatting;
using System.Web.Http;
using System.Web.Http.SelfHost;
using System.Windows.Forms;

namespace SelfHostSample
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        private void startHostButton_Click(object sender, EventArgs e)
        {
            var configuration = new HttpSelfHostConfiguration("http://localhost:8090"); // 기본 주소 설정
            configuration.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            var host = new HttpSelfHostServer(configuration);
            host.OpenAsync().Wait(); // 비동기적으로 호스트 열기

            // 호스트 시작 후 버튼 비활성화
            startHostButton.Enabled = false; 
            MessageBox.Show("Web API 호스트가 http://localhost:8090 에서 시작되었습니다.");
        }
    }
}

packages.config 프로젝트에 설치된 NuGet 패키지 목록입니다.

<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="Microsoft.AspNet.WebApi.Client" version="5.3.0" targetFramework="net48" />
  <package id="Microsoft.AspNet.WebApi.Core" version="5.3.0" targetFramework="net48" />
  <package id="Microsoft.AspNet.WebApi.SelfHost" version="5.3.0" targetFramework="net48" />
  <package id="Newtonsoft.Json" version="13.0.3" targetFramework="net48" />
  <!-- 필요한 경우 다른 종속성 패키지 -->
</packages>

태그: asp.net web api self-host client ip address httpcontextwrapper remoteendpointmessageproperty

7월 11일 00:24에 게시됨