0

I've built an API with C# that works fine when I do a "Get" from Postman.

Now, I'm trying to perform the same "Get" using an HTML web page that I'm building.

Here's my HTML so far:

<!DOCTYPE html>
<html>
    <body>

        <h1>My First Heading</h1>

        <p>My first paragraph.</p>

            <script>
                const Http = new XMLHttpRequest();
                const url='https://localhost:44369';
                Http.open("GET", url);
                Http.send();

                Http.onreadystatechange = (e) => {
                console.log(Http.responseText)
                }

            </script>

    </body>
</html>

And here is the method in my API that I'm trying to perform the "Get" on:

//https://localhost:44369/api/Request
[EnableCors("AllowLocalhostOrigins")]
[HttpGet]
public ActionResult GetText()
{
    
    string a = "b";

    return Ok(a);
}

Here's the Error:

Access to XMLHttpRequest at 'https://localhost:44369/' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I've read about the CORS, but I'm not clear on what I need to do in the HTML to make it work. The API returns the "Get" request just fine in Postman so I know that the API at least functions properly.

Lance U. Matthews
  • 15,725
  • 6
  • 48
  • 68
Jeff
  • 21
  • 7
  • The EnableCors attribute takes in a policy name. Did you set up a matching CORS policy, if so, please edit that into the question so you have a proper [mcve]. If not, you need to [read the documentation again](https://jakeydocs.readthedocs.io/en/latest/security/cors.html). – mason Jun 05 '22 at 01:30

2 Answers2

1

You need to setup a CORS policy in your API. Please see this question -> How to enable CORS in ASP.NET Core The accepted answer ther has links to the MSDN docs.

You can also find a great tutorial here -> C# Corner Cors Tutorial

Your frontend is calling from a specific URL. Your API determines if it wants to grant that request based on its policy about URLs calling it (CORS).

To further clarify, given there are no bugs in your frontend app, there's nothing in it stopping you from calling the API. The API is telling it "no" because the API isn't configured to accept the request from the URL of your frontend.

EDIT

As per the very helpful information given by Mason in the comments below, I was incorrect as to how the permissions are set up with CORS. While you do configure CORS in your API, it is a header-based system that the API provides to your browser. Your browser then knows it is a trusted source and it will allow the information from the server hosting the API to be loaded into the browser. Browser allows API, not API allows call from Browser.

  • This isn't quite an accurate description of how CORS works (honestly, it's pretty misleading). It's not that the API is not configured to accept these requests. CORS is enforced by the client, by browsers. The server side API itself doesn't care if the client uses CORS or not. If a particular client doesn't use CORS, the server is still going to process the requests all the same. The server just tells the client (via a header) what domains the browser should permit loading resources from. For more info, check [docs on MDN](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS). – mason Jun 05 '22 at 23:55
  • Please update your answer to remove the inaccurate information so that it doesn't cause confusion for any future readers. – mason Jun 05 '22 at 23:56
  • It's not splitting hairs. CORS is often misunderstood, and spreading misinformation, even unintentionally, doesn't help. Your last two paragraphs contain wrong information. Please update the language in your answer so that it doesn't make incorrect statements. – mason Jun 07 '22 at 00:17
  • Answers on Stack Overflow have impact beyond helping the original person that asked the question. Dozens, hundreds, or thousands of people may see this answer in the future, people coming here that aren't familiar with the domain. Thus, they're not aware they're reading incorrect information and then have an inaccurate model of how things work in their heads, and may continue spreading that misinformation to others. I appreciate you're trying to help, but care must be taken that any info you provide be correct. If you'd like me to edit your answer to correct the inaccuracies, plz let me know – mason Jun 07 '22 at 00:24
  • @mason Thanks for the information, but you took it too far – Kenneth McManis Jun 07 '22 at 00:27
  • I'm sorry you're taking it that way, as it's not my intention. I'm here to ensure that the quality of our site remains high, so that it will continue to be useful to future visitors. It's not a statement about your knowledge or willingness to help. You even solved the problem here. I would just like you to correct the supporting information in your answer which is not correct. Or to permit me to correct it. – mason Jun 07 '22 at 00:33
  • I respect that. Just understand that I'm also a developer that has used SO for a long time. I know how it works and how often it's used and what impact it might have. I'll edit the answer later on tonight. – Kenneth McManis Jun 07 '22 at 00:41
  • Thank you. I'm sorry if you felt I was calling you out. It seemed to me that you felt the inaccuracies I was pointing out weren't worth correcting, and that's why I felt it necessary to share info about the reach of what you write, to help convince that it's important to not (inadvertently) spread misinfo. I don't generally go look at profiles, I just read people based on the interaction we are having. If I told you something you already know, please forgive me as I deal with people of all different backgrounds that may not know these things. – mason Jun 07 '22 at 00:46
  • If you ping me after you edit, I'll gladly upvote and remove my comments since they'll no longer be necessary. – mason Jun 07 '22 at 00:47
  • @mason Thank you. I don't think you should remove your comments. It shows character in recovery on both our parts. This was also my first attempt at answering a question so I felt a bit vulnerable here. What you shared actually helped me a lot. I learned quite a bit from those docs in comparison to what I answered. – Kenneth McManis Jun 07 '22 at 01:07
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/245373/discussion-between-kenneth-mcmanis-and-mason). – Kenneth McManis Jun 07 '22 at 02:05
0

After changing my Startup.cs file to the following, I no longer get the "Access blocked by CORS policy error."

        public void ConfigureServices(IServiceCollection services)
    {
        /* I added */
        services.AddCors(options =>
        {
            options.AddDefaultPolicy(
                builder =>
                {
                    builder.AllowAnyOrigin()
                                 .AllowAnyMethod()
                                 .AllowAnyHeader();
                                 //.AllowCredentials();
                });
        });

        services.AddControllers();           
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
     
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }          

        app.UseHttpsRedirection();

        app.UseRouting();

        /* I added */
        app.UseCors();
Jeff
  • 21
  • 7