CORS only allowing GET requests .NET/Angular

Discussão em 'Angular' iniciado por Dronius, Janeiro 27, 2025.

  1. Dronius

    Dronius Guest

    I have a service class in Angular where I've placed my API calls:

    import { Injectable } from "@angular/core";
    import { RectangleCoordinates } from "../models/interfaces/RectangleCoordinates";
    import { HttpClient } from "@angular/common/http";
    import { Observable } from "rxjs";

    @Injectable({
    providedIn: "root",
    })
    export class RectangleService {
    readonly RECTANGLE_API = "https://localhost:7192/api/Rectangle";
    constructor(private http: HttpClient) {}

    getRectangleCoordinates(): Observable<RectangleCoordinates> {
    return this.http.get<RectangleCoordinates>(this.RECTANGLE_API);
    }

    updateRectangleCoordinates(rectangleCoords: RectangleCoordinates) {
    this.http.put(this.RECTANGLE_API, rectangleCoords).subscribe();
    }
    }



    In my ASP.NET 6 Web API backend I have my program.cs file set up to allow CORS like this:

    var MyAllowSpecificOrigins = "_myAllowSpecificOrigins";

    var builder = WebApplication.CreateBuilder(args);

    builder.Services.AddCors(options =>
    {
    options.AddPolicy(name: MyAllowSpecificOrigins,
    policy =>
    {
    policy.WithOrigins("http://localhost:4200");
    });
    });

    ....

    app.UseCors(MyAllowSpecificOrigins);



    The GET request works wonderfully, but the PUT request gives me this error:


    Access to XMLHttpRequest at 'https://localhost:7192/api/Rectangle' from origin 'http://localhost:4200' has been blocked by CORS policy: Method PUT is not allowed by Access-Control-Allow-Methods in preflight response.
    ​

    Why could this be? It seems I have enabled CORS properly and why only for GET requests?

    Continue reading...

Compartilhe esta Página