Two ASP.NET web applications - Cross origin reques

2019-08-03 08:47发布

问题:

I created a new solution with two ASP.NET web applications, one MVC application and one Web API.

I wanted to access the api using a subdomain like api.hybridwebapp.com/values so I implemented an IHttpRouteConstraint to ensure request.RequestUri.Host == "api.mydomain.com" on all Api routes. More details in this answer.

Then I added the following line to my host files:

127.0.0.1    hybridwebapp.com  api.hybridwebapp.com

In IIS Manager I created 2 websites (one for each project) and set the appropriate bindings for each website (hybridwebapp.com on 80 & api.hybridwebapp.com on 80)

In the projects' Web properties I set a Local IIS virtual directory at the root of each of those websites:

MVC Project Url: http://hybridwebapp.com

Web Api Project Url: http://api.hybridwebapp.com

I made a click handler in the MVC application to make a cross-domain request to the Web Api and it successfully made it despite me never actually configuring any Cors attributes on the Web Api.

This is misleading because this will clearly fail in production. What can I do to make this more realistic..I'd actually like to tweak the CORS configuration to have a stricter scope but I can't do that when it accepts all requests, even those that should fail..

回答1:

Cross-sub-domain requests are still considered cross-domain requests as different sub-domains can point to entirely different IPs and servers. You'll definitely get errors if you don't set up CORS properly in your production setup.

Edit: To properly emulate production setup, you'll need to play with the IIS binding configuration. If you can't get it working, you shall try a VM for hosting the api.hybridwebapp.com, which will definitely work as CORS is triggered automatically between different servers.