programing

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

newnotes 2023. 3. 11. 09:26
반응형

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

Json을 반환하는 간단한 액션 방법이 있습니다.ajax.example.com에서 실행됩니다.다른 사이트 someothersite.com에서 접속해야 합니다.

전화를 걸려고 하면 예상대로...:

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

이 문제를 회피하는 방법은 JSONP와 헤더를 설정하는 커스텀HttpHandler의 2가지입니다.

더 간단한 방법은 없나요?

간단한 행동이 허용된 출처 목록을 정의하거나 모든 사람을 허용하는 것이 가능하지 않은가?액션 필터?

최적의 방법은...:

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 Web 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를 지원하지 않습니다.프록시를 통해 자동으로 요청을 전송하는 Javascript를 작성했습니다.모두 100% 투명합니다(내 프록시와 스크립트만 포함하면 됩니다).

nuget을 사용하여 하다corsproxy부속의 지시에 따릅니다.

블로그 투고 | 소스 코드

IIS 7+ 를 사용하고 있는 경우는, web.config 파일을 시스템의 폴더 루트에 배치할 수 있습니다.webServer 섹션:

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

참조: http://msdn.microsoft.com/en-us/library/ms178685.aspx 및 http://enable-cors.org/ #how-back7

가 쿠키로때에는 "xhr"이 ).withCredentials=true에는 「」라고 하는 것이 있습니다Access-Control-Allow-Origin*(Crome "Cannot use wildcard in Access-Control-Allow-Origin when credentials " " " " " true " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " "

@jgauffin의 답변을 바탕으로 작성했습니다.이것은 기본적으로 특정 브라우저의 보안 검사를 회피하는 방법이기 때문에 주의사항을 비웁니다.

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

이것은 매우 간단합니다.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>

오리진에서는 웹 서버에 액세스할 수 있는 모든 도메인을, 머리글에는 Ajax http 요청에서 사용할 수 있는 모든 가능한 헤더를, 메서드에는 서버에서 허용하는 모든 메서드를 넣습니다.

경위:)

WebAPI 2 에서는, 「Install-Package Microsoft」를 사용해 인스톨 할 수 있는 CORS 용 패키지가 추가되었습니다.AspNet.WebApi.Cors 프로젝트 전 WebServic

인스톨 되면, 다음의 코드에 따라 주세요.http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api

OPTIONS 동사도 문제를 일으킬 수 있습니다.

간단히: web.config를 다음과 같이 업데이트합니다.

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

또한 httpGet 및 httpOptions를 사용하여 웹 서비스/컨트롤러 헤더를 업데이트합니다.

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

API를 사용하는 경우 메서드에 이 행을 추가합니다.

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

튜토리얼은 매우 유용합니다.간단히 요약하면:

  1. 누게트. CORS.Install-Package Microsoft.AspNet.WebApi.Cors

  2. 고객님의 고객명WebApiConfig.cs, 추가, 추가config.EnableCors()Register()★★★★★★ 。

  3. cors 처리를 위해 필요한 컨트롤러에 Atribute를 추가합니다.

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

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

저녁 내내 고생한 끝에 겨우 이 일을 할 수 있었다.디버깅을 몇 번 한 결과, 문제가 발견되었습니다.이 문제는, 클라이언트가, 제공된 오리진, 메서드, 및 헤더를 사용해 애플리케이션이 투고 요구를 송신할 수 있는지를 확인하기 위해서, 이른바 프리플라이트 옵션 요구를 송신하고 있는 것입니다.Owin이나 APIController를 사용하고 싶지 않아 땅을 파고 Action Filter Attribute만으로 다음 솔루션을 생각해 냈습니다.특히 "Access-Control-Allow-Headers(액세스 제어-허용-헤더)" 부분은 매우 중요합니다.여기서 언급된 헤더는 요청이 전송되는 헤더와 일치해야 합니다.

using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MyNamespace
{
    public class AllowCrossSiteJsonAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            HttpRequest request = HttpContext.Current.Request;
            HttpResponse response = HttpContext.Current.Response;

            // check for preflight request
            if (request.Headers.AllKeys.Contains("Origin") && request.HttpMethod == "OPTIONS")
            {
                response.AppendHeader("Access-Control-Allow-Origin", "*");
                response.AppendHeader("Access-Control-Allow-Credentials", "true");
                response.AppendHeader("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE");
                response.AppendHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, X-RequestDigest, Cache-Control, Content-Type, Accept, Access-Control-Allow-Origin, Session, odata-version");
                response.End();
            }
            else
            {
                HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
                HttpContext.Current.Response.Cache.SetNoStore();

                response.AppendHeader("Access-Control-Allow-Origin", "*");
                response.AppendHeader("Access-Control-Allow-Credentials", "true");
                if (request.HttpMethod == "POST")
                {
                    response.AppendHeader("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE");
                    response.AppendHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, X-RequestDigest, Cache-Control, Content-Type, Accept, Access-Control-Allow-Origin, Session, odata-version");
                }

                base.OnActionExecuting(filterContext);
            }
        }
    }
}

마지막으로 저의 MVC 액션 방식은 이렇습니다.여기서 중요한 것은 Options HttpVersions도 언급하는 것입니다.그렇지 않으면 프리플라이트 요구가 실패하기 때문입니다.

[AcceptVerbs(HttpVerbs.Post | HttpVerbs.Options)]
[AllowCrossSiteJson]
public async Task<ActionResult> Create(MyModel model)
{
    return Json(await DoSomething(model));
}

Access-Control-Expose-Headers를 통과하는 방법은 여러 가지가 있습니다.

  • jgauffin이 설명한 바와 같이 새로운 속성을 생성할 수 있습니다.
  • RendroMatt가 설명한 바와 같이 web.config 파일에 추가할 수 있습니다.
  • 또 다른 방법은 webApiconfig.cs 파일에 다음과 같이 코드를 추가하는 것입니다.

    config.EnableCors(새로운 EnableCorsAttribute()), 헤더: " " 메서드: "*", 표시됨헤더: "TestHeaderToExpose") {SupportsCredentials = true};

또는 Global에 아래 코드를 추가할 수 있습니다.Asax 파일

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

옵션용으로 작성했습니다.필요에 따라 동일하게 수정해 주세요.

해피 코딩!!

저는 DotNet Core MVC를 사용하고 있으며, 몇 시간 동안 nuget 패키지, Startup.cs, 속성 및 이 플레이스와 싸운 후 MVC 액션에 다음과 같이 추가했습니다.

Response.Headers.Add("Access-Control-Allow-Origin", "*");

이게 꽤 투박하다는 건 알지만, 내가 필요한 건 그것뿐이고, 그 헤더를 추가하고 싶은 건 아무것도 없었어.이게 다른 사람에게 도움이 됐으면 좋겠어!

Web.config에 다음과 같이 입력합니다.

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

IIS를 사용하는 경우 IIS CORS 모듈을 사용해 보는 것이 좋습니다.
구성이 쉽고 모든 유형의 컨트롤러에서 작동합니다.

다음에, 설정의 예를 나타냅니다.

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

MVC 5에서 메인 해답이 작동하도록 하기 위해서.

시스템을 사용합니다.시스템 대신 Web.Mvc를 사용합니다.Web.Http.필터

using System;
using System.Web.Mvc;
// using System.Web.Http.Filters;

public class AllowCrossSiteJsonAttribute : ActionFilterAttribute
{
   ...
}

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

반응형