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)