aleczandru
aleczandru

Reputation: 5449

Cross Site ajax request not working

Hi I need to have two standalone projects one will be an MVC project and the other an WEB API project.Both will be placed in separate solutions.

My problem appears when I try to make ajax calls from the mvc project to the web api project and I ge this error:

OPTIONS http://localhost:54599/api/Account/IsCurrentUserAuthenticated 405

(Method Not Allowed) jquery-1.9.1.min.js:5 OPTIONS http://localhost:54599/api/Account/IsCurrentUserAuthenticated Origin http://localhost:61620 is not allowed by Access-Control-Allow-Origin. jquery-1.9.1.min.js:5 XMLHttpRequest cannot load http://localhost:54599/api/Account/IsCurrentUserAuthenticated. Origin http://localhost:61620 is not allowed by Access-Control-Allow-Origin.

After a bit of research I came up with this filter that is added to the controllers to witch I need to make calls:

 public class AllowCrossSiteJsonWebApiAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(System.Web.Http.Filters.HttpActionExecutedContext filterContext)
    {
        filterContext.Response.Headers.Add("Access-Control-Allow-Origin", "*");

        string rqstMethod = filterContext.ActionContext.ControllerContext.Request.Method.Method.ToUpperInvariant();

        if (rqstMethod == "OPTIONS" || rqstMethod == "POST")
        {
            filterContext.Response.Headers.Add("Access-Control-Allow-Methods", "POST, OPTIONS");
            filterContext.Response.Headers.Add("Access-Control-Allow-Headers", "X-Requested-With, Accept, Access-Control-Allow-Origin, Content-Type");
        }

        if (rqstMethod == "OPTIONS")
        {
            filterContext.Response = new HttpResponseMessage(HttpStatusCode.OK);
            return;
        }

        base.OnActionExecuted(filterContext);
    }

    public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext filterContext)
    {
        base.OnActionExecuting(filterContext);
    }
}

ANd this is the call I am making from the client:

 function fetch(url) {
    xhrFields = {
        withCredentials: true // pass auth cookies to server over ajax req
    };

    var options = {
        url: url,
        type: 'GET',
        contentType: "application/json; charset=utf-16",
        dataType: 'json',
        xhrFields: xhrFields
    };

    return $.ajax(options);
}

How can I solve my problem?

Upvotes: 1

Views: 419

Answers (2)

웃웃웃웃웃
웃웃웃웃웃

Reputation: 11984

var options = {
        url: url,
        type: 'GET',
        contentType: "application/json; charset=utf-16",
        dataType: 'jsonp',
        xhrFields: xhrFields
    };

You need to use jsonp datatype while using cross domain.

Upvotes: 2

Blowsie
Blowsie

Reputation: 40525

You need to use dataType: 'jsonp' for crossdomain requests

Upvotes: 1

Related Questions