griegs
griegs

Reputation: 22760

Cors issue across domains

We have a very badly written legacy WebSite application that we are trying to slowly convert to MVC.

As part of this we will be creating a set of MVC controllers that we would like to be able to call from the legacy website as a stopgap measure.

So far I have the following in the website aspx page as an event on the click of a button;

function CallControllerMethod() {
    $.ajax({
        type: 'GET',
        dataType: "text",
        url: "http://localhost:49443/Home/TestAjaxMethod",
        success: function (response) {
            alert(response);
        },
        error: function (e) {
            console.log(e);
        }
    });
}

And this calls a controller method in the MVC project;

[EnableCors("*", "*", "*")]
public class HomeController : Controller
{
    [HttpGet]
    [EnableCors("*","*","*")]
    public int TestAjaxMethod()
    {
        return 10;
    }
}

In the WebApiConfig in the MVC app I have this;

    var cors = new EnableCorsAttribute("*", "*", "*");
    configuration.EnableCors(cors);

So when i call the controller method from the website, my breakpoint in the mvc controller is hit. However, when I return the value of 10, on the website ajax call I get the following error;

XMLHttpRequest cannot load http://localhost:49443/Home/TestAjaxMethod. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:49252' is therefore not allowed access.

What's confusing is that the Ajax call makes it to the controllers method but I can't seem to return the value from it.

Update

Even if I remove all references to Cors from the WebApiConfig and from the controller, the MVC method is still reached and I get the same error.

Upvotes: 2

Views: 97

Answers (1)

Alex Warren
Alex Warren

Reputation: 7547

As noted in the comments, the EnableCors attribute only applies to WebAPI controllers. If you want to add a CORS header to a regular MVC method, you could do it manually.

For example here is some code I've used in the past:

var origin = Request.Headers["Origin"];

if (origin != null)
{
    Response.AddHeader("Access-Control-Allow-Origin", origin);
}

Alternatively, you can create your own attribute:

public class AddCorsHeader : ActionFilterAttribute
{
    public override void OnActionExecuted(HttpActionExecutedContext context)
    {
        IEnumerable<string> origin;
        if (context.Request.Headers.TryGetValues("Origin", out origin))
        {
            context.Response.Headers.Add("Access-Control-Allow-Origin", origin);
        }
    }
}

and then add [AddCorsHeader] to the relevant methods.

Upvotes: 1

Related Questions