0

I'm designing 2 websites, the first in https://localhost:44300/ and the second in https://localhost:44301/.

In the Home controller of the second localhost, I declared:

[HttpPost]
public ActionResult GetPictureUrl
{
   return Json(new { success = true, url = "~/Content/Images/Img001.png" });
}

I wanna get that json in the first localhost after clicking button:

<button>Get picture url</button>
<script>
$('button').click(function () {
   $.ajax({
      url: 'https://localhost:44301/Home/GetPictureUrl',
      type: 'POST',
      //dataType: 'jsonp' //I'd tried this but still not working
   }).done(function (data) {
      if (data.success) {
         alert(data.url)
      }
   })
})
</script>

Here is the error I'd got in Console log:

GET https://localhost:44301/Home/GetPictureUrl?callback=jQuery21407544594064820558_1451364678040&_=1451364678041

Why GET?

I'd set type: 'POST' in the ajax, and I didn't send anything to the controller as a parameter. But as you can see above, what were callback and _?

Tân
  • 1
  • 15
  • 56
  • 102
  • You should use `method: 'post'` instead – Eranda Dec 29 '15 at 05:14
  • @Eranda Sorry, I just try again and get this error message: `XMLHttpRequest cannot load https://localhost:44301/Home/GetPictureUrl. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://localhost:44300' is therefore not allowed access.` – Tân Dec 29 '15 at 05:17
  • It's seems another issue. Go and see this link. It may help you : http://stackoverflow.com/questions/20035101/no-access-control-allow-origin-header-is-present-on-the-requested-resource – Eranda Dec 29 '15 at 05:24
  • 2
    You are making a CORS request which is blocked by browser by default. You will have to find a way to get through it. Refer this link - http://stackoverflow.com/questions/6290053/setting-access-control-allow-origin-in-asp-net-mvc-simplest-possible-method – SBirthare Dec 29 '15 at 05:24

1 Answers1

0

I've solved the problem.

Add these lines to web.config inside <system.webServer> (both of 2 websites)

<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" />
  </customHeaders>
</httpProtocol>

After that, I can use:

$('button').click(function () {
        $.ajax({
            url: 'https://localhost:44301/Home/GetPictureUrl',
            type: 'POST' //or method: 'POST'
        }).done(function (data) {
            if (data.success) {
                alert(data['url'])
            }
        })
    })

Thanks to @Eranda and @SBirthare

Tân
  • 1
  • 15
  • 56
  • 102
  • I hope you are aware that with this generic setting you are opening gates for all your website public methods. This will not be an ideal solution for a production web application. You would want to define a attribute and attach it to ONLY method/controller that needs CORS waiver. – SBirthare Dec 29 '15 at 07:30