EN VI

Asp.net-core - Communication between API and ASP.NET Core MVC web app - does it need "CORS" or not?

2024-03-15 17:00:12
How to Asp.net-core - Communication between API and ASP.NET Core MVC web app - does it need "CORS" or not?

This is my API:

[ApiController] 
[Route("[controller]")]
public class APIController : ControllerBase
{
    // [Authorize]
    [HttpGet("[action]")]
    public string GetInformation() { return "Something !";  }
}

And this is my action in my ASP.NET Core 5 MVC web app:

public async Task<IActionResult> GetInfoFromAPI()
{
    using var client = new HttpClient();

    var requ = new HttpRequestMessage
    {
        Method = HttpMethod.Get,
        RequestUri = new Uri("http://localhost:5000/API/GetInformation"),
        Content = new StringContent(string.Empty, Encoding.UTF8, MediaTypeNames.Application.Json)
    };

    var resp = await client.SendAsync(requ);
    var Result = await resp.Content.ReadAsStringAsync();

    return View("GetInfoFromAPI", Result); 
}

Amazing! How does it work? Why does it work? I didn't enable "Cross-Origin Requests" (CORS) in my API startup !

If any HttpGet/Post/... from any origin can get information from my API, so what is CORS? What is the use for it?

Solution:

To further explain what Yehor said in comments:

Cross-Origin Resource Sharing is a security feature in web browsers whose purpose is to help restrict scripts on one origin (domain) to make requests to another origin. This mechanism was developed to mitigate attacks such as cross-site request forgery (CSRF/XSRF), cross-site scripting (XSS), and other cross-origin attacks. Upon recognizing a cross-origin request, the browsers send an HTTP request to the target server with an "Origin" header. The server then responds with CORS headers indicating whether or not the request is acceptable or not, which depends on the server's CORS policy configuration.

In your case, the CORS policy is not relevant, as two servers are communicating in a back-channel (machine to machine) without involving a browser. In other words, since CORS is a mechanism that is applied at the level of the web browser (front-channel), it does not apply when the two servers are communicating in bnack-channel without a browser involved. Hope this helps.

Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login