Configuración de Access-Control-Allow-Origin en ASP.Net MVC-método más simple posible


Tengo un método de acción simple, que devuelve algo de json. Se ejecuta en ajax.example.com. Necesito acceder a esto desde otro sitio someothersite.com.

Si trato de llamarlo, obtengo lo esperado...:

Origin http://someothersite.com is not allowed by Access-Control-Allow-Origin.

Conozco dos formas de evitar esto: JSONP y crear un HttpHandler personalizado para establece el encabezado.

¿No hay una manera más sencilla?

¿No es posible para una simple acción definir una lista de orígenes permitidos o permitir simplemente ¿todos? Tal vez un filtro de acción?

Óptimo sería...:

return json(mydata, JsonBehaviour.IDontCareWhoAccessesMe);
Author: Community, 2011-06-09

10 answers

Para llano ASP.NET Controladores MVC

Crear un nuevo atributo

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

Etiqueta tu acción:

[AllowCrossSiteJson]
public ActionResult YourMethod()
{
    return Json("Works better?");
}

Para ASP.NET API web

using System;
using System.Web.Http.Filters;

public class AllowCrossSiteJsonAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
        if (actionExecutedContext.Response != null)
            actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Origin", "*");

        base.OnActionExecuted(actionExecutedContext);
    }
}

Etiqueta un controlador API completo:

[AllowCrossSiteJson]
public class ValuesController : ApiController
{

O llamadas individuales a la API:

[AllowCrossSiteJson]
public IEnumerable<PartViewModel> Get()
{
    ...
}

Para Internet Explorer

IE

Descárguelo usando nuget corsproxy y siga las instrucciones incluidas.

Entrada de blog | Código fuente

 340
Author: jgauffin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-02 20:35:59

Si está utilizando IIS 7+, puede colocar una web.archivo config en la raíz de la carpeta del sistema.Sección del servidor web:

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

Véase: http://msdn.microsoft.com/en-us/library/ms178685.aspx Y: http://enable-cors.org/#how-iis7

 107
Author: LaundroMatt,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-07-15 17:08:42

Me encontré con un problema en el que el navegador se negó a servir el contenido que había recuperado cuando la solicitud pasó en las cookies (por ejemplo, el xhr tenía su withCredentials=true), y el sitio tenía Access-Control-Allow-Origin establecido en *. (El error en Chrome fue, " No se puede usar comodín en Access-Control-Allow-Origin cuando la bandera de credenciales es verdadera.")

Basándome en la respuesta de @jgauffin, creé esto, que es básicamente una forma de trabajar en torno a ese control de seguridad del navegador en particular, así que caveat emptor.

public class AllowCrossSiteJsonAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        // We'd normally just use "*" for the allow-origin header, 
        // but Chrome (and perhaps others) won't allow you to use authentication if
        // the header is set to "*".
        // TODO: Check elsewhere to see if the origin is actually on the list of trusted domains.
        var ctx = filterContext.RequestContext.HttpContext;
        var origin = ctx.Request.Headers["Origin"];
        var allowOrigin = !string.IsNullOrWhiteSpace(origin) ? origin : "*";
        ctx.Response.AddHeader("Access-Control-Allow-Origin", allowOrigin);
        ctx.Response.AddHeader("Access-Control-Allow-Headers", "*");
        ctx.Response.AddHeader("Access-Control-Allow-Credentials", "true");
        base.OnActionExecuting(filterContext);
    }
}
 19
Author: Ken Smith,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-09-07 08:30:26

Esto es realmente simple , simplemente agregue esto en la web.config

<system.webServer>
  <httpProtocol>
    <customHeaders>
      <add name="Access-Control-Allow-Origin" value="http://localhost" />
      <add name="Access-Control-Allow-Headers" value="X-AspNet-Version,X-Powered-By,Date,Server,Accept,Accept-Encoding,Accept-Language,Cache-Control,Connection,Content-Length,Content-Type,Host,Origin,Pragma,Referer,User-Agent" />
      <add name="Access-Control-Allow-Methods" value="GET, PUT, POST, DELETE, OPTIONS" />
      <add name="Access-Control-Max-Age" value="1000" />
    </customHeaders>
  </httpProtocol>
</system.webServer>

En Origin ponga todos los dominios que tienen acceso a su servidor web, en encabezados ponga todos los encabezados posibles que cualquier solicitud http ajax puede usar, en métodos ponga todos los métodos que permita en su servidor

Saludos:)

 13
Author: Zvonimir Tokic,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-11 09:54:21

A veces el verbo OPTIONS también causa problemas

Simplemente: Actualiza tu web.config con lo siguiente

<system.webServer>
    <httpProtocol>
        <customHeaders>
          <add name="Access-Control-Allow-Origin" value="*" />
          <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" />
        </customHeaders>
    </httpProtocol>
</system.webServer>

Y actualice los encabezados webservice / controller con HttpGet y httpOptions

// GET api/Master/Sync/?version=12121
        [HttpGet][HttpOptions]
        public dynamic Sync(string version) 
        {
 9
Author: Bishoy Hanna,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-20 11:15:00

WebAPI 2 ahora tiene un paquete para CORS que se puede instalar usando : Install-Package Microsoft.AspNet.WebAPI.Cors-servicio web previo al proyecto

Una vez instalado, siga esto para el código: http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api

 7
Author: Tarun,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-04-12 13:33:17

Agregue esta línea a su método, si está utilizando una API.

HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*"); 
 3
Author: Gopichandar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-03-14 11:10:25

Este tutorial es muy útil. Para dar un breve resumen:

  1. Utilice el paquete CORS disponible en Nuget: Install-Package Microsoft.AspNet.WebApi.Cors

  2. En su archivo WebApiConfig.cs, agregue config.EnableCors() al método Register().

  3. Agregue un atributo a los controladores que necesita para manejar cors:

[EnableCors(origins: "<origin address in here>", headers: "*", methods: "*")]

 3
Author: GrandMasterFlush,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-11 10:47:02
    public ActionResult ActionName(string ReqParam1, string ReqParam2, string ReqParam3, string ReqParam4)
    {
        this.ControllerContext.HttpContext.Response.Headers.Add("Access-Control-Allow-Origin","*");
         /*
                --Your code goes here --
         */
        return Json(new { ReturnData= "Data to be returned", Success=true }, JsonRequestBehavior.AllowGet);
    }
 1
Author: Pranav Labhe,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-04 11:46:24

En la Web.config introduzca la siguiente

<system.webServer>
<httpProtocol>
  <customHeaders>
    <clear />     
    <add name="Access-Control-Allow-Credentials" value="true" />
    <add name="Access-Control-Allow-Origin" value="http://localhost:123456(etc)" />
  </customHeaders>
</httpProtocol>
 0
Author: Elvis,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-27 09:17:54