1

I'm writing a quick and dirty little script to log traffic on a static HTML page. I am making a POST to another server where I have the API hosted. The server has CORS enabled (see code below) but I still get a 405.

    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Allow-Headers" value="*" />
    <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, PATCH, DELETE, OPTIONS" />

Here's my JavaScript:

  var host = window.location.host;
  var hostname = window.location.hostname;
  var href = window.location.href;
  var port = window.location.port;
  var path = window.location.pathname;
  var referrer = document.referrer;

  var obj = { 
    Host: host,
    HostName: hostname,
    Href: href,
    Port: port,
    Path: path,
    Referrer: referrer
  };

  $.ajax({
    type: 'POST',
    url: 'http://localhost/system/api/sp/logvisit',
    data: obj,
    dataType: 'json',
    contentType: 'application/json'
  });

Here is my controller:

namespace Gs.Api
{
    public class SPController : ApiController
    {
        [Route("api/sp/logvisit")]
        [HttpPost]
        public void LogVisit(LogVisitRequest request)
        {
            // do stuff with request
        }
    }
}

I tried the main answer here Handling CORS Preflight requests to ASP.NET MVC actions which got rid of the 405 but my method never actually got called. I tried several other fixes from various answers here and some got rid of the error but my posted object would be null.

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Timothy
  • 1,198
  • 3
  • 10
  • 30

1 Answers1

1

I figured this out on my own. I had to take a few other solutions and use them all together, but I got it finally.

  1. I used this answer: https://stackoverflow.com/a/13646169/3920075
  2. I changed <add name="Access-Control-Allow-Headers" value="*" /> to <add name="Access-Control-Allow-Headers" value="Content-Type" />.
  3. I changed data: obj, to data: JSON.stringify(obj)
Timothy
  • 1,198
  • 3
  • 10
  • 30