Programing

ASP.Net MVC에서 Access-Control-Allow-Origin 설정-가장 간단한 방법

lottogame 2020. 5. 8. 08:15
반응형

ASP.Net MVC에서 Access-Control-Allow-Origin 설정-가장 간단한 방법


나는 간단한 액션 메소드를 가지고 있는데, 이는 json을 반환합니다. ajax.example.com에서 실행됩니다. 다른 사이트 someothersite.com에서이 사이트에 액세스해야합니다.

전화하려고하면 예상대로 얻을 수 있습니다 ... :

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

이 문제를 해결하는 두 가지 방법 인 JSONP헤더를 설정하기 위해 사용자 정의 HttpHandler작성하는 방법을 알고 있습니다.

더 간단한 방법이 없습니까?

간단한 조치로 허용 된 원점 목록을 정의하거나 모든 사람을 허용 할 수 없습니까? 액션 필터일까요?

최적은 ... :

return json(mydata, JsonBehaviour.IDontCareWhoAccessesMe);

일반 ASP.NET MVC 컨트롤러

새로운 속성을 만듭니다

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

작업에 태그를 지정하십시오.

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

ASP.NET 웹 API

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

전체 API 컨트롤러에 태그를 지정하십시오.

[AllowCrossSiteJson]
public class ValuesController : ApiController
{

또는 개별 API 호출 :

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

Internet Explorer <= v9의 경우

IE <= 9는 CORS를 지원하지 않습니다. 프록시를 통해 해당 요청을 자동으로 라우팅하는 자바 스크립트를 작성했습니다. 그것은 모두 100 % 투명합니다 (내 프록시와 스크립트 만 포함하면됩니다).

너겟을 사용하여 다운로드 corsproxy하고 포함 된 지침을 따르십시오.

블로그 게시물 | 소스 코드


IIS 7 이상을 사용하는 경우 system.webServer 섹션에서 web.config 파일을 폴더의 루트에 넣을 수 있습니다.

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

참조 : http://msdn.microsoft.com/en-us/library/ms178685.aspxhttp://enable-cors.org/#how-iis7


I ran into a problem where the browser refused to serve up content that it had retrieved when the request passed in cookies (e.g., the xhr had its withCredentials=true), and the site had Access-Control-Allow-Origin set to *. (The error in Chrome was, "Cannot use wildcard in Access-Control-Allow-Origin when credentials flag is true.")

Building on the answer from @jgauffin, I created this, which is basically a way of working around that particular browser security check, so 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);
    }
}

This is really simple , just add this in 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>

In Origin put all domains that have access to your web server, in headers put all possible headers that any ajax http request can use, in methods put all methods that you allow on your server

regards :)


Sometimes OPTIONS verb as well causes problems

Simply: Update your web.config with the following

<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>

And update the webservice/controller headers with httpGet and httpOptions

// GET api/Master/Sync/?version=12121
        [HttpGet][HttpOptions]
        public dynamic Sync(string version) 
        {

WebAPI 2 now has a package for CORS which can be installed using : Install-Package Microsoft.AspNet.WebApi.Cors -pre -project WebServic

Once this is installed, follow this for the code :http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api


This tutorial is very useful. To give a quick summary:

  1. Use the CORS package available on Nuget: Install-Package Microsoft.AspNet.WebApi.Cors

  2. In your WebApiConfig.cs file, add config.EnableCors() to the Register() method.

  3. Add an attribute to the controllers you need to handle cors:

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


Add this line to your method, If you are using a API.

HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*"); 

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

There are different ways we can pass the Access-Control-Expose-Headers.

  • As jgauffin has explained we can create a new attribute.
  • As LaundroMatt has explained we can add in the web.config file.
  • Another way is we can add code as below in the webApiconfig.cs file.

    config.EnableCors(new EnableCorsAttribute("", headers: "", methods: "*",exposedHeaders: "TestHeaderToExpose") { SupportsCredentials = true });

Or we can add below code in the Global.Asax file.

protected void Application_BeginRequest()
        {
            if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
            {
                //These headers are handling the "pre-flight" OPTIONS call sent by the browser
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "*");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Credentials", "true");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "http://localhost:4200");
                HttpContext.Current.Response.AddHeader("Access-Control-Expose-Headers", "TestHeaderToExpose");
                HttpContext.Current.Response.End();
            }
        }

I have written it for the options. Please modify the same as per your need.

Happy Coding !!


In Web.config enter the following

<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>

If you use IIS, I'd suggest trying IIS CORS module.
It's easy to configure and works for all types of controllers.

Here is an example of configuration:

    <system.webServer>
        <cors enabled="true" failUnlistedOrigins="true">
            <add origin="*" />
            <add origin="https://*.microsoft.com"
                 allowCredentials="true"
                 maxAge="120"> 
                <allowHeaders allowAllRequestedHeaders="true">
                    <add header="header1" />
                    <add header="header2" />
                </allowHeaders>
                <allowMethods>
                     <add method="DELETE" />
                </allowMethods>
                <exposeHeaders>
                    <add header="header1" />
                    <add header="header2" />
                </exposeHeaders>
            </add>
            <add origin="http://*" allowed="false" />
        </cors>
    </system.webServer>

참고URL : https://stackoverflow.com/questions/6290053/setting-access-control-allow-origin-in-asp-net-mvc-simplest-possible-method

반응형