Ajax in different project

Asked

Viewed 728 times

6

I have a project in Asp.Net MVC with the following method:

public ActionResult ObterCursos()
{
    List<curso> cursos = new List<curso>();

    curso curso_ = new curso();
    curso_.Nome = "Análise";
    curso_.Periodo = 3;
    curso_.qtdSemestre = 5;
    curso_.Codigo = "ADS";

    cursos.Add(curso_);

    curso_ = new curso();
    curso_.Nome = "Ciencia da Computação";
    curso_.Periodo = 3;
    curso_.qtdSemestre = 8;
    curso_.Codigo = "CDC";

    cursos.Add(curso_);

    return Json(cursos, JsonRequestBehavior.AllowGet);
}

As you can see, it returns a Json as a result. I am running such project on my local machine.
In another project, I am trying to make an Ajax request to the method created in the project previously described.

$.ajax({
    url : "http://localhost:10642/Mobile/ObterCursos",
    type : "GET",
    dataType : "json",
    success : function(dados) {
        resultado = dados;
        alert("json sucess")
    },
    error : function(xhr, ajaxOptions, error) {
        alert("erro json: " + xhr.responseText)
    }
});

Upon execution, the alert of error is shown and the following error is displayed on the console:

Xmlhttprequest cannot load http://localhost:10642/Mobile/Get courses. No 'Access-Control-Allow-Origin' header is present on the requested Resource. Origin 'null' is therefore not allowed access.

Conducting my research, I discovered I should change the dataType of Ajax for jsonp. And so I did, but alert of error is still shown, however the error that was displayed on console no longer appears.
Can someone help me?

  • This here: url : "http://localhost:10642/Mobile/ObterCursos",is bad practice. Switch to: /Mobile/ObterCursos.

  • 1

    The problem @Ciganomorrisonmendez is that as I said in the problem, Ajax is running on another project.

  • It’s still bad practice. The correct thing is that the beginning of the address comes from Web.config.

  • 1

    Well @Ciganomorrisonmendez the problem is that in my project where Ajax is a project Cordova, in this case how I could set up the Web.config?

  • I think the ideal would be to open a question just for that. They are a few steps, but it is pertinent the separation.

  • 1

    Opa @Ciganomorrisonmendez opened the question well here.

Show 1 more comment

1 answer

5


This error is caused by you making an ajax request from a different domain, probably in your case it is only the port that differs, as both must be on the localhost.

To solve, just add the header Access-Control-Allow-Origin in the server response. One way to do this is to add the following section in the Web.config file:

<system.webServer>

    <httpProtocol>
       <customHeaders>
       <clear />
       <add name="Access-Control-Allow-Origin" value="*" />
       </customHeaders>
    </httpProtocol> 

In this case the attribute value="*" you are freeing up access to any domain, but you can free up to specific domains by changing the * by the domain name (in your case localhost:porta for the development environment).


Another way to add the header is by using a filter

public class AllowOriginAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "*");
        base.OnActionExecuting(filterContext);
    }
}

Then add the attribute to the Controller method:

[AllowOrigin]
public ActionResult ObterCursos()
  • Thank you very much for the @Marcusvinicius reply, but unfortunately the problem persists. Let me clarify my situation a little better. I have a Web project Asp.Net MVC where runs a site normally, and now I created a new controler called Mobile where I want to make Jsons available for an application that will run on mobile phones around. I am developing such an application (which already has contributions from you) using Cordova and testing in my browser only with the HTML pages and the IIS server of the web project running.

  • I figured this was your scenario. I added an alternative that can work better with MVC, including by allowing you to add the header by method.

  • Thank you again for your commitment to help solve my problem @Marcusvinicius, but unfortunately the problem persists. Funny thing is, I put one breakpoint in the method ObterCursos in the Controller of my MVC project and the request is getting there. The problem, I believe, must be in my Ajax.

  • Have you debugged what comes back in your ajax? You can debug js with IE or go by putting Alert() at certain points and see what is being returned in your ajax.

  • Hello @pnet, thanks for the help, but I’ve debugged yes with IE. Ajax request arrives in my controller does everything right, but when he returns to Ajax with the results alert of error is displayed.

  • worked perfectly, just needed to disable the async of Ajax.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.