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);
}
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.
CodePudding user response:
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
You seem confused or misinformed about how your frontend is communicating with your API. 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.
CodePudding user response:
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();