DEV Community

Hozefa Mangalorewala
Hozefa Mangalorewala

Posted on

CORS how to enable them in .NET?

These two URLs have the same origin:
๐—๐—๐—๐—‰๐—Œ://๐—†๐—’-๐—Œ๐—‚๐—๐–พ-๐—‡๐—ˆ-๐Ÿฃ.๐–ผ๐—ˆ๐—†/๐–ฆ๐–พ๐—/๐–ง๐–บ๐—„๐—Ž๐—‡๐–บ๐–ฌ๐–บ๐—๐–บ๐—๐–บ
๐—๐—๐—๐—‰๐—Œ://๐—†๐—’-๐—Œ๐—‚๐—๐–พ-๐—‡๐—ˆ-๐Ÿฃ.๐–ผ๐—ˆ๐—†/๐–ฆ๐–พ๐—/๐– ๐—…๐—…๐–จ๐—Œ๐–ถ๐–พ๐—…๐—…

These URLs have different origins
๐—๐—๐—๐—‰๐—Œ://๐—†๐—’-๐—Œ๐—‚๐—๐–พ-๐—‡๐—ˆ-๐Ÿฃ.๐–ผ๐—ˆ๐—†/๐–ฆ๐–พ๐—/๐–ง๐–บ๐—„๐—Ž๐—‡๐–บ๐–ฌ๐–บ๐—๐–บ๐—๐–บ
๐—๐—๐—๐—‰://๐—†๐—’-๐—Œ๐—‚๐—๐–พ-๐—‡๐—ˆ-๐Ÿฃ.๐—‡๐–พ๐—/๐–ฆ๐–พ๐—/๐– ๐—…๐—…๐–จ๐—Œ๐–ถ๐–พ๐—…๐—…

To facilitate requests from different origins you need to enable CORS in .NET.

In .NET 6 by using the combination of these methods you can enable CORS as per your requirement.

๐€๐ฅ๐ฅ๐จ๐ฐ๐€๐ง๐ฒ๐Ž๐ซ๐ข๐ ๐ข๐ง: This policy allows requests from any origin.

๐–๐ข๐ญ๐ก๐Ž๐ซ๐ข๐ ๐ข๐ง๐ฌ: This policy allows requests from specific origins. You can specify one or more origins as arguments to this method.

๐€๐ฅ๐ฅ๐จ๐ฐ๐€๐ง๐ฒ๐‡๐ž๐š๐๐ž๐ซ: This policy allows requests with any header.

๐–๐ข๐ญ๐ก๐‡๐ž๐š๐๐ž๐ซ๐ฌ: This policy allows requests with specific headers. You can specify one or more headers as arguments to this method.

๐€๐ฅ๐ฅ๐จ๐ฐ๐€๐ง๐ฒ๐Œ๐ž๐ญ๐ก๐จ๐: This policy allows requests with any HTTP method (e.g., GET, POST, PUT, DELETE).

๐–๐ข๐ญ๐ก๐Œ๐ž๐ญ๐ก๐จ๐๐ฌ: This policy allows requests with specific HTTP methods. You can specify one or more methods as arguments to this method.

Few Things to Keep in mind

โœ”๏ธCORS is not a security feature. CORS is a W3C standard that allows a server to relax the same-origin policy.

โœ”๏ธAn API isn't safer by allowing CORS.

โœ”๏ธIt's a way for a server to allow browsers to execute a cross-origin request that otherwise would be forbidden.

โœ”๏ธBrowsers without CORS can't do cross-origin requests.

Top comments (0)