Ajax in different project

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'm running such a project on my local machine. Home In another project, I'm trying to make an Ajax request to the method created in the project described above.

$.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)
    }
});

When it is run,% w of error is shown and the following error is displayed in the console:

  

XMLHttpRequest can not load link .   In 'Access-Control-Allow-Origin' header is present on the requested   resource. Origin 'null' is therefore not allowed access.

Performing my searches, I discovered that I should change the alert from dataType to Ajax . And so I did, but the% error with error is still shown, however the error that was displayed in jsonp no longer appears. Home Can anyone help me?

    
asked by anonymous 05.06.2015 / 04:18

1 answer

5

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

To solve it at once, 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 with value="*" attribute is releasing access for any domain, but can release to specific domains by changing * by domain name (in this case localhost:porta for 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 in the Controller method:

[AllowOrigin]
public ActionResult ObterCursos()
    
05.06.2015 / 05:20