Reputation: 4517
I thought I'd allowed access to all origins but I'm still getting this error.
Access to XMLHttpRequest at 'localhost:60248/api/page/1' from origin 'http://localhost:4200' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
UPDATE the error has now changed after adding suggested code changes. It's now as follows:
Access to XMLHttpRequest at 'http://localhost:60248/api/page/1' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.
In Startup.cs I have this:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy(name: "AllowAll",
builder =>
{
builder.AllowAnyOrigin()
.WithMethods("PUT", "DELETE", "GET");
});
});
In my controller I have this:
[Route("api/[controller]")]
[ApiController]
public class PageController : ControllerBase
{
...
[EnableCors("AllowAll")]
[HttpGet("{id:int}")]
public async Task<IActionResult> GetPageData(int id)
{
...
This is the Angular service that calls the endpoint:
export class PageContentService {
constructor(private http: HttpClient) { }
getContent(id: number): Observable<PageContent> {
let headers = new HttpHeaders();
headers = headers.set('Content-Type', 'application/json');
const httpOptions = {
headers: headers
}
return this.http.get<PageContent>(`http://localhost:60248/api/page/${id}`, httpOptions);
}
}
I thought that would take care of it, but clearly not.
What else do I need to do?
Upvotes: 1
Views: 8398
Reputation: 2814
I think you need two more things:
Like vivek said, in your Configure
method add .UseCors()
to your request pipeline.
Add .AllowAnyHeader()
to the CORS-Config in the policy builder, I think the Content-Type
-Header isn't allowed by default.
Upvotes: 2
Reputation: 1
You need to add the middleware also.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
...
app.UseCors();
...
}
Upvotes: 2