Search code examples
angularpostasp.net-web-apipreflight

Response for preflight has invalid http status code 404 in my angular project while consuming web api


I know that it's CORS problem. I have enabled cors in web api server side. Get method is working fine but while dealing with post method I am facing problem . Please some one answer me with very simple post example both on web api and client side. With explanation of how to deal with preflight, options etc..

Console

1) zone.js:2935 OPTIONS http://localhost:49975/api/Add_Client_/postgoals 404 (Not Found)

2) Failed to load http://localhost:49975/api/Add_Client_/postgoals: Response for preflight has invalid HTTP status code 404.

web.config

<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*"/>
    <add name="Access-Control-Allow-Headers" value="Origin, Content-Type, X-Auth-Token"/>
    <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
    <add name="Content-Type" value="application/json"/>

    <add name="Access-Control-Allow-Credentials" value="true" />
  </customHeaders>
</httpProtocol>

Angular Post method

    save_Goals(){

  let headers : Headers= new Headers();
  //headers.append('Content-Type','application/x-www-form-urlencoded');
  //headers.append("Access-Control-Allow-Origin","true");
  headers.append('Content-Type', 'application/json');

  headers.append('Access-Control-Allow-Origin','*');
  headers.append('Access-Control-Allow-Methods','GET,PUT,POST,DELETE');
  headers.append('Access-Control-Allow-Headers','Content-Type');

  let options = new RequestOptions({ headers: headers });

    return this._http.post('http://localhost:49975/api/Add_Client_/postgoals', {goal:'foo'},options)
   .map(res =>  res.json());
  }

Thank you!


Solution

  • I finally found a work around. what i did is i removed custom headers from web.config file. i.e,

    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*"/>
        <add name="Access-Control-Allow-Headers" value="Origin, Content-Type, X-Auth-Token"/>
        <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
        <add name="Content-Type" value="application/json"/>
    
        <add name="Access-Control-Allow-Credentials" value="true" />
      </customHeaders>
    </httpProtocol>
    

    This content i removed

    and in WebApiConfig.cs i did following changes

    var enableCorsAttribute = new EnableCorsAttribute(origins:"*",headers:"*",methods:"*");
    
                var json = config.Formatters.JsonFormatter;
    
                json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
                config.Formatters.Remove(config.Formatters.XmlFormatter);
    
                config.EnableCors(enableCorsAttribute);
    

    and Controller Looks like this.

    [EnableCors(origins: "*", headers: "*", methods: "*", SupportsCredentials = true)]
        [RoutePrefix("api/Add_Client_")]
        public class Add_Client_Controller : ApiController
        {
    [AcceptVerbs("POST")]
    
            [HttpPost]
            [Route("PostGoals")]
            public string PostGoals(string goal)
            {
                Goal g = new Goal();
                g.Goals = goal;
                db.Goals.Add(g);
                int res = db.SaveChanges();
    
                return ("Success");
            }
    }
    

    and Angular POST Method looks like following

     save_Goals(){
    
      let headers : Headers= new Headers();
            headers.append('Content-Type','application/x-www-form-urlencoded');
        headers.append('Access-Control-Allow-Origin','*');
          headers.append('Access-Control-Allow-Methods','GET,PUT,POST,DELETE');
          headers.append('Access-Control-Allow-Headers','Content-Type');
    
          let options = new RequestOptions({ headers: headers });
        return this._http.post('http://localhost:49975/api/Add_Client_/PostGoals?goal=check',options)
           .map(res =>  res.json());
        }
    

    This is work around to send data with URL.