In my last post, I showed how to enable CORS in ASP.NET WebAPI. I then found out that I have another issue when hosting it in Azure. Azure has a great supporting on the CORS. You could watch a video about how great it is, here
First, I would like to show you how to enable CORS in Azure.
1) Go to Azure portal, click into the App Service of your WebAPI.
2) Then under API Tag, click CORS.
3) Enter “*” or any specified website that you would like to allow CORS.
DONE! That is easy, isn’t it.
But then if you start running your mobile or website, and fire any jQuery to the WebAPI, you will find this error,
“SEC7128: Multiple Access-Control-Allow-Origin headers are not allowed for CORS response.”
If you check in Fiddler, you will find this,
This is because that Azure has enable the CORS and your app also enabled it. So it has more than one entries on “Access-Control-Allow-Origin” which the preflight request does not allow it. Now we could make some changes to the web.config under Azure,
- Go into Azure portal, Under “development Tools” tag and click “Advanced Tools”. In the Detail panel, click “GO”.
- A new browser will pop up and it is showing on the Kudu page.
- Now you have to click “Debug console” –> “CMD”
- An Azure command prompt shows with a window in upper area like a windows explorer which allowing us to browse into different directory in Azure.
- Now browse into “site” –> “wwwroot”, you could found your web.config here.
- In the left hand side, you could then click on the “Edit” (a pencil icon) to edit the web.config of the WebAPI in browser.
- Now you could comment both of the “Access-Control-Allow-Origin” and “Access-control-Allow-Methods”. And then click Save button in the upper area to save your changes.
DONE again. now your website will have only one entry of the “Access-control-Allow-Origin” and “Access-Control-Allow-Methods” and your client app now can fire any jQuery to the WebAPI without any error.
P.S., Azure has improved the handling of the CORS on the “OPTION” issue that I found from the last post.
You could also check here to learn more about the Kudu