Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
[Web.zip]    
(연관된 글이 9개 있습니다.)
(시리즈 글이 3개 있습니다.)
개발 환경 구성: 118. IIS Express - localhost 이외의 호스트 이름으로 접근하는 방법
; https://www.sysnet.pe.kr/2/0/1030

개발 환경 구성: 684. IIS Express로 호스팅하는 웹을 WSL 환경에서 접근하는 방법
; https://www.sysnet.pe.kr/2/0/13389

개발 환경 구성: 685. 로컬에서 개발 중인 ASP.NET Core/5+ 웹 사이트에 대해 localhost 이외의 호스트 이름으로 접근하는 방법
; https://www.sysnet.pe.kr/2/0/13395




IIS Express - localhost 이외의 호스트 이름으로 접근하는 방법

설마, 아직도 Windows 7 + Visual Studio 2010 환경에서 웹 개발을 하면서 IIS Express를 설치하지 않으신 분은 없겠지요? ^^

WebDev도 좋긴 하지만, 몇몇 특정 기능 때문에 IIS를 사용할 수밖에 없는 상황이 발생하지요. 그런 경우, IIS에서 디버깅을 하려면 '관리자 권한'으로 Visual Studio를 실행해야 하는 문제가 걸리는데, 이런 부분이 "IIS Express"를 사용하면 자연스럽게 해결됩니다. (물론, IIS Express도 net.tcp 프로토콜의 WCF 서비스는 감당 못하지만.)

그리 시간이 걸리지 않으니 지금이라도 아래의 사이트에서 다운로드하십시오. ^^

Internet Information Services (IIS) 7.5 Express 
; http://www.microsoft.com/downloads/en/details.aspx?FamilyID=abc59783-89de-4adc-b770-0a720bb21deb




IIS Express가 이제 설치되었으면, 간단한 테스트 환경을 구성해 보겠습니다.

다음과 같은 내용의 3가지 파일을 c:\temp\web에 넣어두고,

(* 첨부 파일에 아래의 소스가 포함되어 있습니다.)
=========== Default.aspx ===========
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
        <asp:HyperLink ID="HyperLink1" runat="server">HyperLink</asp:HyperLink>
    
    </div>
    </form>
</body>
</html>

=========== Default.aspx.cs ===========
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        HyperLink1.Text = "TEST";
    }
}

=========== web.config ===========
<?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0"/>
  </system.web>
</configuration>

IIS Express가 설치된 폴더에 가서 (관리자 권한 없이) 다음과 같이 명령을 내려주면 웹 사이트 호스팅이 시작됩니다.

C:\Program Files (x86)\IIS Express>iisexpress /path:c:\temp\web /port:8500
Copied template config file 'C:\Program Files (x86)\IIS Express\AppServer\applicationhost.config' to '%LOCALAPPDATA%\Temp\iisexpress\applicationhost201142971710826.config'
Updated configuration file '%LOCALAPPDATA%\Temp\iisexpress\applicationhost201142971710826.config' with given cmd line info.
Starting IIS Express ...
Successfully registered URL "http://localhost:8500/" for site "Development Web Site" application "/"
Registration completed
IIS Express is running.
Enter 'Q' to stop IIS Express

Internet Explorer로 확인을 해보면, 다음과 같이 ^^ default.aspx/cs 파일이 잘 컴파일되어 출력이 되는 것을 확인할 수 있습니다.

how_to_use_hostname_in_iisexpress_1.png

그런데, "http://127.0.0.1:8500"으로 한번 접근해 볼까요? 그러면 다음과 같이 오류가 발생하는 것을 볼 수 있습니다.

how_to_use_hostname_in_iisexpress_2.png

Bad Request - Invalid Hostname
 
HTTP Error 400. The request hostname is invalid.

HttpWebRequest로 호출하면 오류 메시지는 다음과 같은 식으로 나옵니다.
System.Net.WebException
  HResult=0x80131509
  Message=The remote server returned an error: (400) Bad Request.
  Source=System
  StackTrace:
   at System.Net.HttpWebRequest.GetResponse()

말 그대로, IIS Express는 기본적으로 'localhost' 이외의 호스트 이름으로 전달되는 모든 HTTP 요청을 거부합니다. "127.0.0.1" 주소도 거부될 정도이니, 다른 IP나 DNS는 굳이 확인할 필요도 없습니다.

개발자 컴퓨터에서 Visual Studio로 웹 사이트 개발/디버깅하는 용도로는 이런 제약이 크게 문제가 안 되지만, IIS Express 자체가 Tomcat과 같은 무료 웹 서버로 사용되기 위한 용도로는 적합하지 않은 제약입니다.

물론, 이러한 제약을 벗어나도록 하는 방법이 있고 바로 여기서부터 '관리자 권한'이 필요하게 됩니다. 우선, 여러분이 호스트하려는 (포트 포함) URL 형식에 대해 시스템에 등록해 주어야 합니다. 이를 위해 netsh이 필요합니다. 예전에도 몇몇 글에서 한번 알아본 적이 있지요. ^^

WCF 인증서 설정 관련 오류 정리
; https://www.sysnet.pe.kr/2/0/869

VS.NET 2008 - WCF를 위한 디버깅 환경 개선
; https://www.sysnet.pe.kr/2/0/522

그렇습니다. 보안이라는 맥락으로 모두 다 같이 영향을 받는 것으로, 로컬에서 함부로 http.sys와 연동되는 서비스 포트를 열 수 없도록 이러한 제약이 생긴 것입니다. 따라서, 이를 허용하도록 '관리자 권한'에서 설정을 해주어야 하는데, 이 글에서 원하는 것은 8500번 포트를 여는 것이므로 다음과 같이 명령행 창에서 실행해 주면 됩니다.

[형식]: netsh http add urlacl url=http://*:[포트번호]/ user="[사용자 계정]"

C:\Program Files (x86)\IIS Express>netsh http add urlacl url=http://*:8500/ user="testusr32"

URL reservation successfully added

아래와 같은 명령어로 확인을 할 수 있고,

C:\Program Files (x86)\IIS Express>netsh http show urlacl

URL Reservations:
-----------------
    ...[생략]...

    Reserved URL            : http://*:8500/
        User: TESTPC\TESTUSR32
            Listen: Yes
            Delegate: No
            SDDL: D:(A;;GX;;;S-1-5-21-15120209-1487767885-450303533-1000)

지우는 방법은 다음과 같습니다. (실습을 위해 지우지는 마세요. ^^)

netsh http delete urlacl ur=http://*:8500/

이렇게 해서 8500번 포트를 등록했으면 다시 iisexpress를 실행시켜 봅니다. 하지만, 이번에는 정상적으로 실행이 안 됩니다.

C:\Program Files (x86)\IIS Express>iisexpress /path:c:\temp\web /port:8500
Copied template config file 'C:\Program Files (x86)\IIS Express\AppServer\applicationhost.config' to '%LOCALAPPDATA%\Temp\iisexpress\applicationhost201142974455237.config'
Updated configuration file '%LOCALAPPDATA%\Temp\iisexpress\applicationhost201142974455237.config' with given cmd line info.
Starting IIS Express ...
Failed to call HttpAddUrl with http://localhost:8500/
Failed to register URL "http://localhost:8500/" for site "Development Web Site" application "/". Error description: Access is denied. (0x80070005)
Registration completed
Failed to process sites
Report ListenerChannel stopped due to failure; ProtocolId:http, ListenerChannelId:0
HostableWebCore activation failed.
Unable to start iisexpress.

Access is denied.
For more information about the error, run iisexpress.exe with the tracing switch enabled (/trace:error).

일단 netsh로 등록이 되면, 이제 더 이상 localhost만으로 접근이 되는 낮은 권한의 웹 사이트 호스팅이 안 됩니다.

이 단계에서, 한 가지 더 수정을 해주어야 합니다. 즉, "localhost" 이외의 주소로 바인딩하려 한다는 정보를 iisexpress.exe에게 알려야 합니다.

그런데, 아쉽게도 바인딩 관련 옵션을 직접적으로 iisexpress.exe의 명령행 인자로 줄 수 있는 방법이 없습니다. 대신에, 해당 웹 사이트에 대한 호스팅 정보를 제공하는 applicationHost.config 파일을 만들어서 iisexpress.exe에 지정해 주어야 합니다.

다행히 어려운 방법은 아닙니다. applicationHost.config 파일을 바닥부터 만들 필요없이, 이미 iisexpress.exe가 대략적인 호스팅 정보를 담고 있는 config 파일을 만들어주므로 이를 재사용하면 되기 때문입니다. 위의 iisexpress.exe 실행 결과를 자세히 보시면 다음과 같은 경로에 config 파일을 만들어 주고 있음을 눈치챌 수 있습니다.

Updated configuration file '%LOCALAPPDATA%\Temp\iisexpress\applicationhost201142974455237.config' with given cmd line info.


위의 경로에 있는 applicationhost201142974455237.config 파일을 c:\temp\web 폴더에 "applicationhost.config"라는 이름으로 복사하고, bindings 절에서 다음의 내용을 수정해 줍니다.

<sites>
    <site name="Development Web Site" id="1" serverAutoStart="true">
        <application path="/">
            <virtualDirectory path="/" physicalPath="c:\temp\web" />
        </application>
        <bindings>
            <binding protocol="http" bindingInformation=":8500:" /> <== 원래는 ":8500:localhost"
        </bindings>
    </site>
    ...[생략]...
</sites>

자, 이제 다시 명령행에서 다음과 같이 입력해 주면 정상적으로 호스팅이 되는 것을 확인할 수 있습니다.

C:\Program Files (x86)\IIS Express>iisexpress /config:c:\temp\web\applicationHost.config
Starting IIS Express ...
Failed to add localhost binding to binding ':8500:'
Successfully registered URL "http://*:8500/" for site "Development Web Site" application "/"
Registration completed for site "Development Web Site"
IIS Express is running.
Enter 'Q' to stop IIS Express

이유는 알 수 없지만 중간에 failed... 되었다는 메시지가 나오는데 영향은 없습니다. 이제 IP든 도메인 주소든 다음과 같이 정상적으로 접근하는 것이 가능합니다.

how_to_use_hostname_in_iisexpress_3.png




그 외, 위의 사항에 대한 공식적인 문서는 다음의 경로에서 제공됩니다.

Handling URL Binding Failures in IIS Express 
- Serving External Traffic
; http://learn.iis.net/page.aspx/1005/handling-url-binding-failures-in-iis-express/

참고로, '송원석'님이 위의 문서를 번역해서 공개해 주고 있습니다. ^^

No. 61 :: IIS 7.0 인스퍼레이션 - 41, (Handling URL Binding Failures in IIS Express 번역 및 주해) 
; http://www.egocube.pe.kr/asp_0061.asp



[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 5/10/2024]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 



2011-04-30 09시48분
[송원석] 안녕하세요? 송원석입니다.
항상 좋은 글들, 잘 읽고 있습니다.

감사합니다.
[guest]
2011-04-30 09시51분
아... ^^ 넵. 글을 수정했습니다.
정성태
2019-03-25 11시29분
혹시 저렇게 설정했는데도 다음과 같은 오류가 발생한다면?

Service Unavailable
HTTP Error 503. The service is unavailable.

명령행에서 직접 IISExpress.exe를 해당 인자들과 함께 실행해 보세요. 그 이후로는 비주얼 스튜디오에서 잘 되는 경우가 있습니다.
정성태
2021-07-31 05시58분
[gwise] .net core로 rest api서버 만들어서 Xamarin 으로 개발중인데 ip 접근이 안되서 정리해 봤습니다.
위에 처럼 하다가 안되서 아래 처럼 하면 로컬 pc ip로 접근해서 디버깅 할 수 있습니다.

1.Visual Studio 를 관리자 권한으로 실행. (포트번호 8500 번으로 변경)

2. 프로젝트를 한번 실행 한다.

Enable SSL 체크 해제 하고 (http로 실행)

3. 프로젝트 폴더의 ".vs" 폴더로 들어 간다.

C:\Users\DELL\source\repos\WebApplication4\.vs

4. config 폴더에서

C:\Users\DELL\source\repos\WebApplication4\.vs\WebApplication4\config

5. config폴더에서 applicationhost.config 파일을 열람 후 빨간줄 처럼 해준다.

      <site name="WebApplication4" id="2">

        <application path="/" applicationPool="WebApplication4 AppPool">

          <virtualDirectory path="/" physicalPath="C:\Users\DELL\source\repos\WebApplication4\WebApplication4" />

        </application>

        <bindings>

          <binding protocol="http" bindingInformation=":8500:" />

        </bindings>

      </site>

이렇게 하면 ip로 접근이 가능하다.
[guest]

... 91  92  93  94  95  96  97  98  99  100  101  [102]  103  104  105  ...
NoWriterDateCnt.TitleFile(s)
11382정성태12/4/201721879오류 유형: 436. System.Data.SqlClient.SqlException (0x80131904): Connection Timeout Expired 예외 발생 시 "[Pre-Login] initialization=48; handshake=1944;" 값의 의미
11381정성태11/30/201718263.NET Framework: 702. 한글이 포함된 바이트 배열을 나눈 경우 한글이 깨지지 않도록 다시 조합하는 방법(두 번째 이야기)파일 다운로드1
11380정성태11/30/201718315디버깅 기술: 109. windbg - (x64에서의 인자 값 추적을 이용한) Thread.Abort 시 대상이 되는 스레드를 식별하는 방법
11379정성태11/30/201719047오류 유형: 435. System.Web.HttpException - Session state has created a session id, but cannot save it because the response was already flushed by the application.
11378정성태11/29/201720505.NET Framework: 701. 한글이 포함된 바이트 배열을 나눈 경우 한글이 깨지지 않도록 다시 조합하는 방법 [1]파일 다운로드1
11377정성태11/29/201719819.NET Framework: 700. CommonOpenFileDialog 사용 시 사용자가 선택한 파일 목록을 구하는 방법 [3]파일 다운로드1
11376정성태11/28/201724140VS.NET IDE: 123. Visual Studio 편집기의 \r\n (crlf) 개행을 \n으로 폴더 단위로 설정하는 방법
11375정성태11/28/201718950오류 유형: 434. Visual Studio로 ASP.NET 디버깅 중 System.Web.HttpException - Could not load type 오류
11374정성태11/27/201724042사물인터넷: 14. 라즈베리 파이 - (윈도우의 NT 서비스처럼) 부팅 시 시작하는 프로그램 설정 [1]
11373정성태11/27/201723034오류 유형: 433. Raspberry Pi/Windows 다중 플랫폼 지원 컴파일 관련 오류 기록
11372정성태11/25/201726097사물인터넷: 13. 윈도우즈 사용자를 위한 라즈베리 파이 제로 W 모델을 설정하는 방법 [4]
11371정성태11/25/201719690오류 유형: 432. Hyper-V 가상 스위치 생성 시 Failed to connect Ethernet switch port 0x80070002 오류 발생
11370정성태11/25/201719608오류 유형: 431. Hyper-V의 Virtual Switch 생성 시 "External network" 목록에 특정 네트워크 어댑터 항목이 없는 경우
11369정성태11/25/201721706사물인터넷: 12. Raspberry Pi Zero(OTG)를 다른 컴퓨터에 연결해 가상 키보드 및 마우스로 쓰는 방법 (절대 좌표, 상대 좌표, 휠) [1]
11368정성태11/25/201727294.NET Framework: 699. UDP 브로드캐스트 주소 255.255.255.255와 192.168.0.255의 차이점과 이를 고려한 C# UDP 서버/클라이언트 예제 [2]파일 다운로드1
11367정성태11/25/201727367개발 환경 구성: 337. 윈도우 운영체제의 route 명령어 사용법
11366정성태11/25/201719040오류 유형: 430. 이벤트 로그 - Cryptographic Services failed while processing the OnIdentity() call in the System Writer Object.
11365정성태11/25/201721293오류 유형: 429. 이벤트 로그 - User Policy could not be updated successfully
11364정성태11/24/201723199사물인터넷: 11. Raspberry Pi Zero(OTG)를 다른 컴퓨터에 연결해 가상 마우스로 쓰는 방법 (절대 좌표) [2]
11363정성태11/23/201723122사물인터넷: 10. Raspberry Pi Zero(OTG)를 다른 컴퓨터에 연결해 가상 마우스 + 키보드로 쓰는 방법 (두 번째 이야기)
11362정성태11/22/201719669오류 유형: 428. 윈도우 업데이트 KB4048953 - 0x800705b4 [2]
11361정성태11/22/201722438오류 유형: 427. 이벤트 로그 - Filter Manager failed to attach to volume '\Device\HarddiskVolume??' 0xC03A001C
11360정성태11/22/201722253오류 유형: 426. 이벤트 로그 - The kernel power manager has initiated a shutdown transition.
11359정성태11/16/201721737오류 유형: 425. 윈도우 10 Version 1709 (OS Build 16299.64) 업그레이드 시 발생한 문제 2가지
11358정성태11/15/201726512사물인터넷: 9. Visual Studio 2017에서 Raspberry Pi C++ 응용 프로그램 제작 [1]
11357정성태11/15/201726995개발 환경 구성: 336. 윈도우 10 Bash 쉘에서 C++ 컴파일하는 방법
... 91  92  93  94  95  96  97  98  99  100  101  [102]  103  104  105  ...