ChatGPT解决这个技术问题 Extra ChatGPT

Using Custom Domains With IIS Express

Traditionally I use custom domains with my localhost development server. Something along the lines of:

dev.example.com
dev.api.example.com

This has provided me a ton of flexibility when working with external APIs such as Facebook. This has worked great in the past with the built-in Visual Studio Development Server because all I needed to do was add a CNAME to those DNS records pointing to 127.0.0.1.

However, I have not been able to get this to work with IIS Express. Everything I have tried seems to have failed. I have even added the correct XML config to the applicationHost.config file for IIS Express, but it doesn't seem to recognize the entries as valid as a true install of IIS would.

<binding protocol="http" bindingInformation="*:1288:dev.example.com" />

Whenever I enter this line and try to request http://dev.example.com:1288 I get the following message:

Bad Request - Invalid Hostname

Does anybody know if I am missing something obvious? Or did the IIS Express team really lack the foresight to see this type of use?

Make sure you have the applicationPool attribute of the application node set to either "Clr2IntegratedAppPool" or "Clr4IntegratedAppPool". I got the Bad Hostname error you are seeing when using "Clr2ClassicAppPool" or "Clr4ClassicAppPool".
confused - CNAME records do not accept ip addresses but other host names instead. Did you mean A record?
I had lots of issues with this and found it much easier to just use IIS instead of IIS Express
I just ran into this as well. I was hoping it would just look at the port number and ignore the domain. No such luck. Wish I could enable "accept all" on the port....
Vote now! I've added a UserVoice suggestion: visualstudio.uservoice.com/forums/121579-visual-studio/…

s
stimms

This is what worked for me (Updated for VS 2013, see revision history for 2010, for VS 2015 see this: https://stackoverflow.com/a/32744234/218971):

Right-click your Web Application Project ▶ Properties ▶ Web, then configure the Servers section as follows: Select IIS Express ▼ from the drop down Project Url: http://localhost Override application root URL: http://dev.example.com Click Create Virtual Directory (if you get an error here you may need to disable IIS 5/6/7/8, change IIS's Default Site to anything but port :80, make sure Skype isn't using port 80, etc.) Optionally: Set the Start URL to http://dev.example.com Open %USERPROFILE%\My Documents\IISExpress\config\applicationhost.config (Windows XP, Vista, and 7) and edit the site definition in the config block to be along the lines of the following: If running MVC: make sure the applicationPool is set to one of the "Integrated" options (like "Clr2IntegratedAppPool"). Open your hosts file and add the line 127.0.0.1 dev.example.com. ► Start your application!

Some great advice from the comments:

You may need to run Visual Studio as Administrator. If you want to make other devs see your IIS run netsh http add urlacl url=http://dev.example.com:80/ user=everyone If you want the site to resolve for all hosts set bindingInformation="*:80:". Use any port you want, 80 is just convenient. To resolve all hosts you'll need to run Visual Studio as an administrator


This is exactly what I did, was about to write this up, but you beat me to the punch :-) As a side note, if you want to let other dev's see your IIS you may want to do something like "netsh http add urlacl url=dev.example.com:80 user=everyone"
Also, if you want the site to resolve for all hosts, you can use: bindingInformation="*:80:" I use this so localtunnel.com works.
I was getting an access denied error. Running VS 2012 as admin fixed it.
what version of IIS Express is this? I'm running VS2012 (which I believe is IIS Express 8.0), and when I click on the "Use Local IIS Server" radiobutton under the "Servers" area of the Web properties page, click the Use IIS Express checkbox, and then try to put in "mydev.example.com", then hit the "Create Virtual Directory" button, I get this error "Unable to create the virtual directory. Cannot create the Web site mydev.example.com". You must specify "localhost" for the server name.
This is complicated. One must change seetings on several different places. It is easy to make a real mess. Is there really no simpler way?
A
Antoine Meltzheim

For Visual Studio 2015 the steps in the above answers apply but the applicationhost.config file is in a new location. In your "solution" folder follow the path, this is confusing if you upgraded and would have TWO versions of applicationhost.config on your machine.

\.vs\config

Within that folder you will see your applicationhost.config file

Alternatively you could just search your solution folder for the .config file and find it that way.

I personally used the following configuration:

https://i.stack.imgur.com/1IQXV.png

With the following in my hosts file:

127.0.0.1       jam.net
127.0.0.1       www.jam.net

And the following in my applicationhost.config file:

<site name="JBN.Site" id="2">
    <application path="/" applicationPool="Clr4IntegratedAppPool">
        <virtualDirectory path="/" physicalPath="C:\Dev\Jam\shoppingcart\src\Web\JBN.Site" />
    </application>
    <bindings>
        <binding protocol="http" bindingInformation="*:49707:" />
            <binding protocol="http" bindingInformation="*:49707:localhost" /> 
    </bindings>
</site>

Remember to run your instance of visual studio 2015 as an administrator! If you don't want to do this every time I recomend this:

How to Run Visual Studio as Administrator by default

I hope this helps somebody, I had issues when trying to upgrade to visual studio 2015 and realized that none of my configurations were being carried over.


The crucial part is to add the second *:49707: binding instead of replacing the default *:49707:localhost as suggested in many other answers. And you have to run VS as an administrator, indeed (sic!). Thank you.
You could also use a URL like http://jam.127.0.0.1.xip.io/ if you don't want modify your hosts file. Plus, any collaborators won't need to modify theirs. See xip.io.
I think it worth to note that folder ".vs" is hidden and should be made visible at first
I have confirmed that this works in Visual Studio 2017 as well. Interestingly, I did not need both elements (just the first one without "localhost"). Visual Studio, however, certainly does need to be running as Administrator, which is sort of annoying
I just wish there was a way for those of us who are not allowed to run anything administratively to do this. Employers/clients who blanket ban admin privilege without any thought as to how they might safely enable this are incredibly short sighted.
J
Jon

When using Visual Studio 2012 with IIS Express, changing an existing binding does not work permanently. (It may work until you close VS, but after that, things get really messed up.)

The key is keeping the existing localhost binding and adding a new binding after it.

Unless you're running as administrator, you'll also need to run netsh add urlacl (to give yourself permissions to run a non-localhost site as a standard user).

If you want to allow any host name, the full process is as follows:

Create your web application, and find out what port it is using (see project properties, Web tab, Project Url). From an administrator prompt, run the following commands (replacing portnumber with the port number you figured out in #1): netsh http add urlacl url="http://*:portnumber/" user=everyone netsh http add urlacl url="http://localhost:portnumber/" user=everyone

You can also use your user name (DOMAIN\USER) instead of everyone for better security.

Open applicationhost.config (usually under My Documents\IIS Express\config), and find the element with your port number. Add one more binding with the host name you want (in this case, *). For example:

Note that, if want to open up all host names (*), you'll need two netsh commands (one for * and one for localhost). If you only want to open up a specific host name, you don't strictly need the second netsh command (localhost); just the one with your specific host name is sufficient.


Did the same (1st approach), when browsing to mycustomhost:myportnr I get "Service Unavailable". VS2012. I can't try the 2nd as there is no IIS Express under "My Documents" and applicationhost.config I found in c:\Program files\IIS Express had no config for my web application...
With VS2013, I find that this configuration only works if I then run as admin! (Running as non-admin, IIS Express seems to ignore the 2nd binding - if I open its UI from the notification icon, IIS shows my site as running, but only shows the first binding, and I can only use localhost... If I'm running as admin, it shows both bindings in the UI, and both work.) I've added the urlacls with netsh, but this appears to make no difference - IIS Express seems not to even try and bind anything other than localhost if it's not elevated.
Adding a record with the * solved the "Service Unavailable" it for me.
What about a scenario that you need to use HTTPS on port 443?
@Kixoka I am trying to run HTTPS. I managed to get it working but the browser complains that the certificate does not match the domain. I get past that but all resources then fail to load so no images, scripts or CSS.
J
Jaro Dunajsky

The invalid hostname indicates that the actual site you configured in the IIS Express configuration file is (most likely) not running. IIS Express doesn't have a process model like IIS does.

For your site to run it would need to be started explicitly (either by opening and accessing from webmatrix, or from command line calling iisexpress.exe (from it's installation directory) with the /site parameter.

In general, the steps to allow fully qualified DNS names to be used for local access are Let's use your example of the DNS name dev.example.com

edit %windows%\system32\drivers\etc\hosts file to map dev.example.com to 127.0.0.1 (admin privilege required). If you control DNS server (like in Nick's case) then the DNS entry is sufficient as this step is not needed. If you access internet through proxy, make sure the dev.example.com will not be forwared to proxy (you have to put in on the exception list in your browser (for IE it would be Tools/Internet Options/Connections/Lan Settings, then go to Proxy Server/Advanced and put dev.example.com on the exeption list. Configure IIS Express binding for your site (eg:Site1) to include dev.example.com. Administrative privilege will be needed to use the binding. Alternatively, a one-time URL reservation can be made with http.sys using netsh http add urlacl url=http://dev.example.com:/ user= start iisexpress /site:Site1 or open Site1 in WebMatrix


Hi Jaro, thanks for the help, but 127.0.0.1 is set in my DNS not the hosts file so that all the developers have the same access. Second I cannot get it to start debugging in VS, unless the binding is set as "*:1234:localhost" which is a totally useless setup, because it is bound to all IP addresses on my machine but only accepts host headers of "localhost". Why didn't they just do "127.0.0.1:1234:" and avoid all this crap. Host headers are not needed as long as the IP and port resolve. And running as Admin is just a huge pain in the ass for a large team. What a disaster IIS Express is.
Also just as a reference Bad Request - Invalid Hostname means that the hostname I am trying to use cannot resolve because the IIS Express team in their infinite wisdom decided to specifically call out "localhost" as the only host header that would work. And VS won't let you run it any other way other than "*:1234:localhost"
I hear you on the 127.0.0.1 issue. The "localhost" in the binding is definitely a pain since it doesn't include traffic for 127.0.0.1 . The design is limited by today's contract of http.sys (http protocol handler) that only recognizes "localhost" for the non-administrative use. The admin only requirement can be mitigated by one-time URL reservation with http.sys (will update the information above). Please let me know you exact use with Visual Studio (it is VS2010 with SP1 Beta?). Let's try to work on this some more and (hopefully) settle the issue.
note - if you see netsh.exe error 87 the parameter is incorrect - may be because you omitted an URI path (/) after your hostname.
r
rymo

On my WebMatrix IIS Express install changing from "*:80:localhost" to "*:80:custom.hostname" didn't work ("Bad Hostname", even with proper etc\hosts mappings), but "*:80:" did work--and with none of the additional steps required by the other answers here. Note that "*:80:*" won't do it; leave off the second asterisk.


uuuum, so "*:80:*" worked for me, but then I restarted my computer and it suddenly wouldn't work until I changed it to "*:80:" and all was well! Thanks.
Finally!! Also followed all the steps elsewhere, and removing the * at the end made it work, thanks!
Just here to say that this worked for me. I tried the accepted answer and reverted all changes down to what you said and all works great. I am using VS2013 Update4.
This seems to work perfectly. When using VS2017, I'm not sure what to place in the Project Url to have it write that in the applicationhost.config file? Is it possible to set through VS IDE?
J
Jon

Like Jessa Flint above, I didn't want to manually edit .vs\config\applicationhost.config because I wanted the changes to persist in source control. I also didn't want to have a separate batch file. I'm using VS 2015.

https://i.stack.imgur.com/maVFN.png


::The following configures IIS Express to bind to any address at the specified port

::remove binding if it already exists
"%programfiles%\IIS Express\appcmd.exe" set site "MySolution.Web" /-bindings.[protocol='http',bindingInformation='*:1167:'] /apphostconfig:"$(SolutionDir).vs\config\applicationhost.config"

::add the binding
"%programfiles%\IIS Express\appcmd.exe" set site "MySolution.Web" /+bindings.[protocol='http',bindingInformation='*:1167:'] /apphostconfig:"$(SolutionDir).vs\config\applicationhost.config"

Just make sure you change the port number to your desired port.


One minor addition here. Make sure to create rules to open that port in your Windows Firewall. Then it worked like a charm!
I like your answer because editing the .vs\config\applicationhost.config is not feasible when multiple developers run IIS Express on their own machines. Thank you!
D
Daniel B. Chapman

I was trying to integrate the public IP Address into my workflow and these answers didn't help (I like to use the IDE as the IDE). But the above lead me to the solution (after about 2 hours of beating my head against a wall to get this to integrate with Visual Studio 2012 / Windows 8) here's what ended up working for me.

applicationhost.config generated by VisualStudio under C:\Users\usr\Documents\IISExpress\config

    <site name="MySite" id="1">
        <application path="/" applicationPool="Clr4IntegratedAppPool">
            <virtualDirectory path="/" physicalPath="C:\Users\usr\Documents\Visual Studio 2012\Projects\MySite" />
        </application>
        <bindings>
            <binding protocol="http" bindingInformation="*:8081:localhost" />
            <binding protocol="http" bindingInformation="*:8082:localhost" />
            <binding protocol="http" bindingInformation="*:8083:192.168.2.102" />
        </bindings>
    </site>

Set IISExpress to run as Administrator so that it can bind to outside addresses (not local host)

Run Visual Stuio as an Administrator so that it can start the process as an administrator allowing the binding to take place.

The net result is you can browse to 192.168.2.102 in my case and test (for instance in an Android emulator. I really hope this helps someone else as this was definitely an irritating process for me.

Apparently it is a security feature which I'd love to see disabled.


J
Jesse Flint

The up-voted answer is valid.. and this information helped me quite a bit. I know this topic has been discussed before but I wanted to add some additional input. People are saying that you must "manually edit" the application.config file in the Users IISExpress/Config directory. This was a big issue for me because I wanted to distribute the configuration via Source control to various developers.

What I found is that you can automate the updating of this file using the "C:\Program Files\IIS Express\appcmd.exe" program. It took a while to find out the control parameters but Ill share my findings here. Essentially you can make a .bat file that runs both the NETSH command and the APPCMD.EXE (and perhaps swap out a host file if you like) to make host header configuration easy with IIS Express.

Your install bat file would look something like this:

netsh http add urlacl url=http://yourcustomdomain.com:80/ user=everyone 

"C:\Program Files\IIS Express\appcmd.exe" set site "MyApp.Web" /+bindings.[protocol='http',bindingInformation='*:80:yourcustomdomain.com']

I also will make a "Uninstall" bat file that will clean up these bindings..(because often times Im just faking out DNS so that I can work on code that is host name sensitive)

netsh http delete urlacl url=http://yourcustomdomain.com:80/

"C:\Program Files\IIS Express\appcmd.exe" set site "MyApp.Web" /-bindings.[protocol='http',bindingInformation='*:80:yourcustomdomain.com']

I hope this information is helpful to someone.. It took me a bit to uncover.


H
Haddad

This method has been tested and worked with ASP.NET Core 3.1 and Visual Studio 2019.

.vs\PROJECTNAME\config\applicationhost.config

Change "*:44320:localhost" to "*:44320:*".

<bindings>
    <binding protocol="http" bindingInformation="*:5737:localhost" />
    <binding protocol="https" bindingInformation="*:44320:*" />
</bindings>

Both links work:

https://localhost:44320

https://127.0.0.1:44320

Now if you want the app to work with the custom domain, just add the following line to the host file:

C:\Windows\System32\drivers\etc\hosts

127.0.0.1 customdomain

Now:

https://customdomain:44320

NOTE: If your app works without SSL, change the protocol="http" part.


I get "Unable to connect to web server 'IIS Express'." because of that asterisk
you unfortunately must run visual studio as administrator for this to work. I have tried the netssh thing and other stuff and only thing that has worked is running visual studio as administrator
N
Neil Monroe

Following Jaro's advice, I was able to get this working under Windows XP and IIS Express (installed via Web Matrix) with a small modification and was not limited to only localhost. It's just a matter of setting the bindings correctly.

Use WebMatrix to create a new site from folder in your web application root. Close WebMatrix. Open %USERPROFILE%\My Documents\IISExpress\config\applicationhost.config (Windows XP. Vista and 7 paths will be similar) and edit the site definition in the config block to be along the lines of the following:

If running MVC, then keep the applicationPool set to one of the "Integrated" options.


T
TylerH

David's solution is good. But I found the <script>alert(document.domain);</script> in the page still alerts "localhost" because the Project Url is still localhost even if it has been override with http://dev.example.com. Another issue I run into is that it alerts me the port 80 has already been in use even if I have disabled the Skype using the 80 port number as recommended by David Murdoch. So I have figured out another solution that is much easier:

Run Notepad as administrator, and open the C:\Windows\System32\drivers\etc\hosts, add 127.0.0.1 mydomain, and save the file; Open the web project with Visual Studio 2013 (Note: must also run as administrator), right-click the project -> Properties -> Web, (lets suppose the Project Url under the "IIS Express" option is http://localhost:33333/), then change it from http://localhost:33333/ to http://mydomain:333333/ Note: After this change, you should neither click the "Create Virtual Directory" button on the right of the Project Url box nor click the Save button of the Visual Studio as they won't be succeeded. You can save your settings after next step 3. Open %USERPROFILE%\My Documents\IISExpress\config\applicationhost.config, search for "33333:localhost", then update it to "33333:mydomain" and save the file. Save your setting as mentioned in step 2. Right click a web page in your visual studio, and click "View in Browser". Now the page will be opened under http://mydomain:333333/, and in the page will alert "mydomain".

Note: The port number listed above is assumed to be 33333. You need to change it to the port number set by your visual studio.

Post edited: Today I tried with another domain name and got the following error: Unable to launch the IIS Express Web server. Failed to register URL... Access is denied. (0x80070005). I exit the IIS Express by right clicking the IIS Express icon at the right corner in the Windows task bar, and then re-start my visual studio as administrator, and the issue is gone.


now, this is the answer that should be considered as the proper solution ! Make sure you edit the applicationhost.config located in .vs/config if you are using visual studio 2015.
M
Morten Aslo-Petersen

I tried all of above, nothing worked. What resolved the issue was adding IPv6 bindings in the hosts file. In step 5 of @David Murdochs answer, add two lines instead of one, i.e.:

127.0.0.1 dev.example.com
::1 dev.example.com

I figured it out by checking $ ping localhost from command line, which used to return:

Reply from 127.0.0.1: bytes=32 time<1ms TTL=128

Instead, it now returns:

Reply from ::1: time<1ms

I don't know why, but for some reason IIS Express started using IPv6 instead of IPv4.


d
dan

Just in case if someone may need...

My requirement was:

SSL enabled

Custom domain

Running in (default) port: 443

Setup this URL in IISExpress: http://my.customdomain.com

To setup this I used following settings:

Project Url: http://localhost:57400

Start URL: http://my.customdomain.com

/.vs/{solution-name}/config/applicationhost.config settings:

<site ...>
    <application>
        ...
    </application>
    <bindings>
        <binding protocol="http" bindingInformation="*:57400:" />
        <binding protocol="https" bindingInformation="*:443:my.customdomain.com" />
    </bindings>
</site>

My IIS Express website fails to launch after making these changes. Can you share your launchSettings.json file?
t
trd

I was using iisexpress-proxy (from npm) for this.

https://github.com/icflorescu/iisexpress-proxy


Does this still work for you? I ran into issues having to install openssl just to get it to run, and even then it gives errors about keys being too small.
M
MW247

Leaving this here just in case anyone needs...

I needed to have custom domains for a Wordpress Multisite setup in IIS Express but nothing worked until I ran Webmatrix/Visual Studio as an Administrator. Then I was able to bind subdomains to the same application.

<bindings> 
    <binding protocol="http" bindingInformation="*:12345:localhost" />
    <binding protocol="http" bindingInformation="*:12345:whatever.localhost" />
</bindings>

Then going to http://whatever.localhost:12345/ will run.