Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between AllowedHosts in appsettings.json and UseCors in .NET Core API 3.x

Tags:

c#

.net

.net-core

I see that .NET Core 3.x comes with a new special configuration AllowedHosts used to list hosts allowed to access the site while this option already exists with CORS (app.UseCors).

What's the difference between these two options?

like image 761
omar saidi Avatar asked Jan 15 '20 10:01

omar saidi


People also ask

What is AllowedHosts?

As per the documentation, allowedHosts is used for host filtering to bind your app to specific hostnames. For example, if you replace following: "AllowedHosts": "*" with "AllowedHosts": "example.com" and you try to access your app using http://localhost:xxxx/ address you will get default bad request (400) response.

What is the use of Appsettings json in .NET Core?

The appsettings. json file is generally used to store the application configuration settings such as database connection strings, any application scope global variables, and much other information.

Can we have multiple Appsettings json?

Of course, we can add and use multiple appsettings. json files in ASP.NET Core project. To configure and read data from your custom json files, you can refer to the following code snippet.


1 Answers

As per the documentation, allowedHosts is used for host filtering to bind your app to specific hostnames. For example, if you replace following:

"AllowedHosts": "*" 

with

"AllowedHosts": "example.com" 

and you try to access your app using http://localhost:xxxx/ address you will get default bad request (400) response.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd"> <HTML>  <HEAD>     <TITLE>Bad Request</TITLE>     <META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii">     </ HEAD>  <BODY>     <h2>Bad Request - Invalid Hostname</h2>     <hr>     <p>HTTP Error 400. The request hostname is invalid.</p> </BODY>  </HTML> 

Because of the host-filtering middleware not allowing the app to bind the app to any other hostname except example.com.

CORS

CORS, on the other hand, is to control which hosts try accessing a resource (API) on your app.

like image 107
TheVillageIdiot Avatar answered Sep 28 '22 06:09

TheVillageIdiot