Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Access-Control-Allow-Origin with MVC

I'm trying to get simple cross domain call working with a simple HTML with JQuery page and an MVC site on another domain.

I'm basing what I do on this ...

Setting Access-Control-Allow-Origin in ASP.Net MVC - simplest possible method

Here's the call in my simple site ...

    <script type="text/javascript">
        $(function () {
            $.get("http://example.com:20874/Home/YourMethod", function (data) {
                alert(data);
            });

        });
    </script>

and heres my controller ... the attribute code is just pasted from other question ...

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    [AllowCrossSiteJson]
    public ActionResult YourMethod()
    {
        return Json(@"{""title"": ""example glossary""}");
    }

}

But the calling site errors with ...

XMLHttpRequest cannot load http://example.com:20874/Home/YourMethod. Origin http://example.com:90 is not allowed by Access-Control-Allow-Origin.

Can anyone assist please?

like image 529
Andy Clarke Avatar asked May 23 '13 11:05

Andy Clarke


People also ask

What is Cors MVC?

Cross Origin Resource Sharing (CORS) is a W3C standard that allows a server to relax the same-origin policy. Using CORS, a server can explicitly allow some cross-origin requests while rejecting others. CORS is safer and more flexible than earlier techniques such as JSONP.


1 Answers

Gave up with the attributes and just did it like this ...

    public ActionResult YourMethod()
    {
        HttpContext.Response.AppendHeader("Access-Control-Allow-Origin", "*");
        return Json(@"{""title"": ""example glossary""}");
    }
like image 193
Andy Clarke Avatar answered Sep 29 '22 15:09

Andy Clarke