65

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?

Pang
  • 9,564
  • 146
  • 81
  • 122
omar saidi
  • 753
  • 1
  • 5
  • 4

1 Answers1

87

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.

Community
  • 1
  • 1
TheVillageIdiot
  • 40,053
  • 20
  • 133
  • 188
  • 31
    Technically speaking CORS isn't going to disallow calls to the API, but it disallows the browser to render the response. The call is still made. – mslot Apr 04 '20 at 10:29
  • 3
    can we add multiple entries to the allowed hosts section as comma separated or something? like "localhost,devserver.domain" or something like that? – Ak777 May 18 '20 at 06:22
  • 3
    @Ak777 yes, you can. The value is a semicolon-delimited list of host names without port numbers, e.g. `example.com;localhost`. – Emiel Koning Jun 17 '20 at 14:11
  • 2
    @TheVillageIdiot In which situation this can be helpfull ? – Muflix Oct 12 '20 at 14:37
  • What exactly does having `"AllowedHosts": "example.com"` do? Like does it prevent some sort of attack? – variable Jan 14 '22 at 11:50
  • how about IpAddresses ITest something `"AllowedHosts": "localhost;1xx.7x.82x.53x"` like but its not worked – Ramin Azali Nov 20 '22 at 12:29
  • @RaminAzali As the property name suggest, `AllowedHosts` requires hostnames, not IP addresses. It does not say `AllowedIP` for a reason. – Codingwiz Mar 07 '23 at 15:34