0

Tengo una aplicación en Angular 4 que consume un servicio en ASP .Net Core y no hay ningún problema. Esta misma aplicación también consume datos de otro servicio pero este es en ASP .Net es un API REST,

Este es el codigo de mi Servicio

    [HttpGet]
    [Route("api/Documentos/getString")]
    public string getString()
    {
        return "ok";
    }

y asi es como lo estoy consumiendo desde Angular

  constructor(private httpClient: HttpClient) {
      this.header = { headers: new HttpHeaders({ 'Content-Type': 'application/json' })};
  }

  getString(): Observable<any> {
       return this.httpClient.get("http://localhost:60402/api/Documentos/getString", this.header);
  }

El error que me da es el siguiente. introducir la descripción de la imagen aquí

Quizá me falta agregar algo en el webConfig pero la verdad no lo se, ¿alguna solución?

4
  • Tu aplicación servidora está retornando un 405 (Method not allowed). Esto es porque el navegador, antes de hacerle la petición GET desde javascript, hace una petición previa OPTIONS y analiza la respuesta del servidor buscando ciertas cabeceras. Si el servidor responde como un error (como es tu caso), o si las cabeceras que busca no están presentes, el navegador aborta la petición. Debes asegurarte de que el servidor admite el verbo OPTIONS sobre esa ruta y que retorna las cabeceras CORS apropiadas. No sé cómo se hace eso en ASP .NET :-(
    – abulafia
    el 19 oct. 2018 a las 22:32
  • Mira a ver si esta información de Microsoft sobre CORS en ASP.NET te ayuda
    – abulafia
    el 19 oct. 2018 a las 22:34
  • he seguido lo que dice el link, agregue config.EnableCors(); en WebApiConfig.Register y agregue [EnableCors(origins: "", headers: "", methods: "*")] en mi controlador pero sigue sucediendo lo mismo
    – Hersenfels
    el 20 oct. 2018 a las 0:28
  • ahora me aparece "Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header contains multiple values '*, *', but only one is allowed. Origin 'localhost:4200' is therefore not allowed access."
    – Hersenfels
    el 20 oct. 2018 a las 0:42

1 respuesta 1

0

This works for me:

Web.config

httpProtocol

customHeaders

<add name="Access-Control-Allow-Origin" value="*" />

<add name="Access-Control-Allow-Methods" value="*" />

<add name="Access-Control-Allow-Headers" value="x-requested-with, Content-Type, origin, authorization, accept, client-security-token" />

Global.asax

protected void Application_BeginRequest() { if (Request.Headers.AllKeys.Contains("Origin") && Request.HttpMethod == "OPTIONS") { // These headers are handling the "pre-flight" OPTIONS call sent by the browser HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE"); HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept"); HttpContext.Current.Response.AddHeader("Access-Control-Allow-Credentials", "true"); HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000"); HttpContext.Current.Response.End();
} }

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.