My application is not working, I installed the Microsoft Cors package to my Web API in visual studio, I enabled origins and I think properly configured my controllers and services in angular7, but the problem persisted.

ERROR: Solicitud de origen cruzado bloqueada: La misma política de origen no permite la lectura de recursos remotos en http://localhost:57319/api/Product. (Razón: Solicitud CORS sin éxito).

ERROR Error: "Uncaught (in promise): HttpErrorResponse: {"headers":{"normalizedNames":{},"lazyUpdate":null,"headers":{}},"status":0,"statusText":"Unknown Error","url":"http://localhost:57319/api/Product","ok":false,"name":"HttpErrorResponse","message":"Http failure response for http://localhost:57319/api/Product: 0 Unknown Error","error":{"isTrusted":true}}"

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Web.Http.Cors;

namespace ProjectAPI
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            //Enable CORS
            config.EnableCors(new EnableCorsAttribute("http://localhost:4200", headers: "*", methods: "*"));


            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}

service class Angular

import { Injectable } from '@angular/core';
import { Product } from './product.model';
import { HttpClient } from "@angular/common/http";

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

  formData : Product;
  list : Product[];
  readonly rootURL = "http://localhost:57319/api";

  constructor(private http : HttpClient) { }

  postProduct(formData : Product){
   return this.http.post(this.rootURL+'/Product',formData);    
  }

  refreshList(){
    this.http.get(this.rootURL+'/Product')
    .toPromise().then(res => this.list = res as Product[]);
  }

  putProduct(formData : Product){
    return this.http.put(this.rootURL+'/Product/'+formData.ProductID,formData);

   }

   deleteProduct(id : number){
    return this.http.delete(this.rootURL+'/Product/'+id);
  }
}

0 Answers