'Cross-Origin Request Blocked: Angular 13 and ASP.Net Core Web API 6

I am facing a problem while submitting the form using the POST method in the REST API. Though get methods are working nicely. I have added both server-side and front-end code snippets.

Server Side (ASP.NET Core Web API 6)

Card-Api/Program.cs

using Card_Api.Data;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

// Injecting DbContex
builder.Services.AddDbContext<CardsDbContext>(
    options => options.UseSqlServer(
        builder.Configuration.GetConnectionString("DefaultConnection")
        )
    );

builder.Services.AddCors(options =>
    {
        options.AddPolicy(
            name: "AllowOrigin",
            builder =>
            {
                builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();
            });
    });



var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseCors("AllowOrigin");

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

Card-Api/Controller/CardsController.cs

using Card_Api.Data;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace Card_Api.Controllers;

[EnableCors("AllowOrigin")]
[ApiController]
[Route("api/[Controller]")]
public class CardsController : Controller
{
    private readonly CardsDbContext cardsDbContext;
    public CardsController(CardsDbContext cardsDbContext)
    {
        this.cardsDbContext = cardsDbContext;
    }
    
    // GET all cards
    [HttpGet] // Kills 2 hours for not implementing
    public async Task<IActionResult> GetAllCards()
    {
        var cards = await cardsDbContext.Cards.ToListAsync();
        return Ok(cards);
    }
    
    
    // Get single card
    [HttpGet]
    [Route("{id:guid}")]
    [ActionName("GetCard")]
    public async Task<IActionResult> GetCard([FromRoute] Guid id)
    {
        var card = await cardsDbContext.Cards.FirstOrDefaultAsync(
            x => x.id == id);
        if (card != null)
        {
            return Ok(card);
        }
        return NotFound("Sorry, card did not found!");
    }

    
    // Add single card
    [HttpPost]
    [EnableCors("AllowOrigin")]
    [Route("{id:guid}")]
    public async Task<IActionResult> AddCard([FromBody] Models.Card card)
    {
       card.id = Guid.NewGuid();
        await cardsDbContext.Cards.AddAsync(card);
        await cardsDbContext.SaveChangesAsync();

        return CreatedAtAction(nameof(GetCard), new {id = card.id}, card);
    }
    
// Updating a card
    [HttpPut]
    [Route("{id:guid}")]
    public async Task<IActionResult> UpdateCard([FromRoute]Guid id, [FromBody] Models.Card card)
    {
        var existingCard = await cardsDbContext.Cards.FirstOrDefaultAsync(
            x => x.id == id);
        if (card != null)
        {
            existingCard.CardHolderName = card.CardHolderName;
            existingCard.CardNumber = card.CardNumber;
            existingCard.ExpiryMonth = card.ExpiryMonth;
            existingCard.ExpiryYear = card.ExpiryYear;
            existingCard.CVC = card.CVC;
            
            await cardsDbContext.SaveChangesAsync();

            return Ok(existingCard);
        }
        return NotFound("Card not found!");
    }


    // Deleting a card
    [HttpDelete]
    [Route("{id:guid}")]
    public async Task<IActionResult> DeleteCard([FromRoute] Guid id)
    {
        var existingCard = await cardsDbContext.Cards.FirstOrDefaultAsync(
            x => x.id == id);
        if (existingCard != null)
        {
            cardsDbContext.Remove(existingCard);
            await cardsDbContext.SaveChangesAsync();
            return Ok(existingCard);
        }
        return NotFound("Card not found!");
    }
}

And the front-end side (Angular 13):

Project/src/service/cards.service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpInterceptor,
  HttpRequest,
  HttpErrorResponse,
  HttpHandler,
  HttpEvent,
  HttpResponse } from '@angular/common/http'
import { Card } from '../Model/card.model';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class CardsService {

  baseUrl = 'https://localhost:7134/api/Cards'


  constructor(private http: HttpClient) { }

  // Get all cards
  getAllCards(): Observable<Card[]> {
    return this.http.get<Card[]>(this.baseUrl);
  }

  // Post data
  addCard(card: Card): Observable<Card> {
    card.id = '00000000-0000-0000-0000-000000000000';
    return this.http.post<Card>(this.baseUrl, card);
  }
}

appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "DefaultConnection": "Server=GG\\SQLEXPRESS;Database=CardsDb;user id=GG;Password=GG2022;Trusted_Connection=true;TrustServerCertificate=True"
  }
}

Project/src/app.component.ts

import { Component, OnInit } from '@angular/core';
import { Card } from './Model/card.model';
import { CardsService } from './service/cards.service';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'cards-web';
  cards: Card[] = [];
  card: Card = {
    id: '',
    cardHolderName: '',
    cardNumber: '',
    expiryMonth: '',
    expiryYear: '',
    cVC: '',
  }

  constructor(private CardsService: CardsService){

  }
  ngOnInit(): void {
    this.getAllCards();
  }

  getAllCards(){
    this.CardsService.getAllCards()
    .subscribe(
      response =>{
        console.log(response);
        this.cards = response;
      }
    );
  }

  onSubmit(){
    console.log(this.card)
    this.CardsService.addCard(this.card)
    .subscribe(
      response =>{
        this.getAllCards();
        this.card = {
          id: '',
          cardHolderName: '',
          cardNumber: '',
          expiryMonth: '',
          expiryYear: '',
          cVC: '',
        };
      },
      error => console.log("Error: ", error)
    )
    }
  }

I can fetch the data from the API. But while submitting the form it shows the following error

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://localhost:7134/api/Cards. (Reason: CORS request did not succeed). Status code: (null).

NB: I have tried using proxy.conf.json and it also did not work. I was following this youtube tutorial.



Solution 1:[1]

Thanks, everyone for the help.

I tried to pass id in the POST method. It worked after removing id route from the controller.

// Adding single card
    [HttpPost]
    public async Task<IActionResult> AddCard([FromBody] Models.Card card)
    {
        card.id = Guid.NewGuid();
        await cardsDbContext.Cards.AddAsync(card);
        await cardsDbContext.SaveChangesAsync();

        return CreatedAtAction(nameof(GetCard), new {id = card.id}, card);
    }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mohammad Jafrin Hossain