0

I made a web api in asp.net to send emails and tested it with postman, the request there works fine, but when I try to call it using an AJAX call it gives me a '405 (Method Not Allowed) error' and 'Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:11495' is therefore not allowed access.'

I don't know what's wrong, I already tried enabling and disabling cross-origin-resource sharing with a chrome extention and it still won't work. What am I doing wrong?

I'm calling the api from another project but both are on localhost at the moment.

Any help is appreciated, I've been stuck for hours.

Here's the AJAX call:

var emailObj = {};
    emailObj.Subject = timelineObj.Subject;
    emailObj.Body = timelineObj.Body;
    emailObj.SendTo = ["test@email.com"]; 
    emailObj.CCTo = [];

    $.ajax({
        type: "POST",
        async: false,
        url: "http://localhost:16627/sendemail",
        data: JSON.stringify({ emailParams: emailObj }),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {
            $.unblockUI();
            console.log(data.d);

        },
        error: function (data) {
            $.unblockUI();
            console.log(data.d);
            alert("An error has occurred during processing your request. [ADD EMAIL]");
        }
    });

Here's the api method:

        [Route("sendemail")]
        [HttpPost]
        public string[] SendEmail(EmailParams emailParams)
        {
            using (GoalEntities db = new GoalEntities()) {

                Goal_Emails ge = new Goal_Emails();
                try
                {
                    BEMail mail = new BEMail();
                    string from = ge.SentFrom = GetParameterByName("EmailUsername").Value;
...

Screenshot of the postman test working fine

  • Possible Duplicate of: https://stackoverflow.com/questions/35588699/response-to-preflight-request-doesnt-pass-access-control-check – Jack Oct 15 '18 at 17:12
  • Have you enabled CORS in your ASP.NET WebAPI? https://docs.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api – Mohsin Mehmood Oct 15 '18 at 17:31

1 Answers1

0

Thanks to Mohsin's comments I found that I hadn't enabled CORS in my webapi.

Followed this tutorial https://docs.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api and everything worked fine.