수색…


WebAPI 2 용 CORS 활성화

// Global.asax.cs calls this method at application start
public static void Register(HttpConfiguration config)
{
    // New code
    config.EnableCors();
}

//Enabling CORS for controller after the above registration
[EnableCors(origins: "http://example.com", headers: "*", methods: "*")]
public class TestController : ApiController
{
    // Controller methods not shown...
}

웹 API 2에서 CORS를 전역 적으로 활성화

public static void Register(HttpConfiguration config)
{
    var corsAttr = new EnableCorsAttribute("http://example.com", "*", "*");
    config.EnableCors(corsAttr);
}

모든 도메인 및 방법에 대해 Asp.Net 5에서 CORS 사용

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
    {
        builder.AllowAnyOrigin()
               .AllowAnyMethod()
               .AllowAnyHeader();
    }));

    // ...
}

public void Configure(IApplicationBuilder app)
{
    app.UseCors("MyPolicy");

    // ...
}

특정 도메인 및 방법에 대해 Asp.Net 5에서 CORS 사용

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddCors();
    services.ConfigureCors(options =>
         options.AddPolicy("AllowSpecific", p => p.WithOrigins("http://localhost:1233")
                                                   .WithMethods("GET")
                                                   .WithHeaders("name")));
}

Windows 인증을 사용하여 CORAP for WebAPI 2 구성

다음 서버 쪽 구성을 사용하면 CORS 요청이 Windows 인증과 함께 작동합니다 (IIS에서 익명을 사용할 수 없도록 설정해야 함).

web.config - 인증되지 않은 (익명) 프리 플라이트 요청 허용 (OPTIONS)

<system.web>
    <authentication mode="Windows" />
    <authorization>
        <allow verbs="OPTIONS" users="*"/>
        <deny users="?" />
    </authorization>
</system.web>

global.asax.cs - 다른 도메인의 발신자가 데이터를 수신 할 수 있도록 허용하는 헤더로 올바르게 회신합니다.

protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
    if (Context.Request.HttpMethod == "OPTIONS")
    {
        if (Context.Request.Headers["Origin"] != null)
            Context.Response.AddHeader("Access-Control-Allow-Origin", Context.Request.Headers["Origin"]);

        Context.Response.AddHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, MaxDataServiceVersion");
        Context.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        Context.Response.AddHeader("Access-Control-Allow-Credentials", "true");

        Response.End();
    }
}

CORS 가능

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // all requests are enabled in this example. SupportsCredentials must be here to allow authenticated requests          
        var corsAttr = new EnableCorsAttribute("*", "*", "*") { SupportsCredentials = true };
        config.EnableCors(corsAttr);
    }
}

protected void Application_Start()
{
    GlobalConfiguration.Configure(WebApiConfig.Register);
}

웹 API 2 엔드 포인트에 대해 jQuery에서 인증 된 요청을 올바르게 전송하십시오.

다음 예제에서는 Web API 2에 대해 GET 및 POST 요청을 올바르게 작성하는 방법을 보여줍니다 (CORS는 다른 도메인에서 전송 된 경우 서버 측으로 구성해야 함).

<script type="text/javascript" src="https://code.jquery.com/jquery-3.1.1.js"></script>
CORS with Windows Authentication test
<script type="text/javascript">

    // GET
    $.ajax({
        url: "endpoint url here",
        type: "GET",
        dataType: "json",
            xhrFields: {
            withCredentials: true
        }
    })
    .done(function (data, extra) {
      alert("GET result" + JSON.stringify(data));
    })
    .fail(function(data, extra) {
    });
    
    //POST
    $.ajax({
        url: "url here",
        type: "POST",
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify({testProp: "test value"}),
        xhrFields: {
            withCredentials: true
        },
        success: function(data) { 
            alert("POST success - " + JSON.stringify(data)); 
        }
    })
    .fail(function(data) {
        alert("Post error: " + JSON.stringify(data.data));
    });
    
</script>

서버 측 코드 :

    [System.Web.Http.HttpGet]
    [System.Web.Http.Route("GetRequestUsername")]
    public HttpResponseMessage GetRequestUsername()
    {
        var ret = Request.CreateResponse(
            HttpStatusCode.OK,
            new { Username = SecurityService.GetUsername() });
        return ret;
    }

    [System.Web.Http.HttpPost]
    [System.Web.Http.Route("TestPost")]
    public HttpResponseMessage TestPost([FromBody] object jsonData)
    {
        var ret = Request.CreateResponse(
            HttpStatusCode.OK,
            new { Username = SecurityService.GetUsername() });
        return ret;
    }

Web API 2 엔드 포인트에 대한 AngularJS의 인증 된 요청을 올바르게 보냅니다.

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.js"></script>
CORS with Windows Authentication test (Angular)
<script type="text/javascript">

    var app = angular.module('myApp', []);
    app.controller('myCtrl', function($http) {
    
        $http(
            {    
                method: 'GET',
                url: 'url here',
                withCredentials: true,
            }
        )
        .then(function(data) {
            alert("Get result = " + JSON.stringify(data.data));
        },
        function(data, extra) {
            alert("Get failed: " + JSON.stringify(data.data));
        });

        $http(
            {
                method: 'POST',
                url: "url here", 
                withCredentials: true,
                data: { url: "some url", message: "some message", type: "some type"}
            }
        )
        .then(function(data) {
            alert("POST success - " + JSON.stringify(data.data));
        },
        function(data) {
            alert("POST failed: " + JSON.stringify(data.data));
        });
    });

</script>
    
<div ng-app="myApp" ng-controller="myCtrl">
</div>


Modified text is an extract of the original Stack Overflow Documentation
아래 라이선스 CC BY-SA 3.0
와 제휴하지 않음 Stack Overflow