Search code examples
angularasp.net-web-apiangular6angular-httpclient

not able to post my form from angular 6 app to asp.net web api


I am trying to post some form data from my angular 6 app to my web api. However, I always get an error message 'OPTIONS http://localhost:52994/api/Mail/SendMail 405 (Method Not Allowed)' and 'Access to XMLHttpRequest at 'http://localhost:52994/api/Mail/SendMail' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.' I am writing all the necessary code for clarity but feel free to ask more if its not clear.

angular method:

sendMail(mail:Mail) {
      console.log(mail); // prints desired data
      this.http.post('http://localhost:52994/api/Mail/SendMail',mail)
      .subscribe(
        data => { console.log ("POST was successful",data)},
        error => { console.log("Error",error)}
      );
   }

where Mail model is as below:

export class Mail {
Name: string;
Email: string;
Message: string;
To: string;
From: string;
}

Here's the target web api method:

[HttpPost]
public HttpResponseMessage SendMail([FromBody]MailModel mail)
{
     try
        {
            using (MailMessage mm = new MailMessage(mail.From, mail.To))
            {
                mm.Subject = "ContactUs";
                string body = "You've got a message as below :";
                body += "<br /><br />Name : " + mail.Name;
                body += "<br /><br />Email : " + mail.Email;
                body += "<br /><br />Message : " + mail.Message;
                mm.Body = body;
                mm.IsBodyHtml = true;
                ....
                smtp.Send(mm);
                return Request.CreateResponse(HttpStatusCode.OK, mail);
            }
        }
        catch(Exception e)
        {
            return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
        }
    }

model class:

   public class MailModel
{
    public string Name { get; set; }
    public string Email { get; set; }
    public string Message { get; set; }
    public string To { get; set; }
    public string From { get; set; }
}

I have set all the required headers in the web.config file as below:

 <httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Allow-Headers" value="Content-Type" />
    <add name="Access-Control-Allow-Methods" value="GET,POST,PUT,DELETE,OPTION" />
  </customHeaders>
</httpProtocol>

Solution

  • Got this working by installing Cors and enabling Cors as below :

      // Enable CORS for the Angular App
      var cors = new EnableCorsAttribute("http://localhost:4200", "*", "*");
      config.EnableCors(cors);