2017-04-05 7 views
1

ASP.NET MVC Ajax를 사용하는 양식이있는 사이트가 있습니다. BeginForm 방법의 예 : 때문에 Url.Action 방법의에서 Request.Url.Scheme PARAM의, URL을 브라우저에서이 점점 도메인이 아닌 다른 도메인으로 설정되고 있음을ASP.NET MVC Ajax 양식이 도메인 간 전송 된 쿠키를 보내지 않았습니다.

@using (Ajax.BeginForm("HandleSignin", "Profile", null, new AjaxOptions() { 
     HttpMethod = "POST", 
     Url = Url.Action("HandleSignin", "Profile", null, Request.Url.Scheme), 
     OnBegin = "SetWithCredentialsTrue(xhr)", 
     InsertionMode = InsertionMode.Replace, 
     UpdateTargetId = "signin-form-container" }, 
    new { id = "sign-in-form", @class = "text-left-desktop group" })) 
{ 
    @Html.AntiForgeryToken() 
    @Html.TextBoxFor(x => Model.Email, new { placeholder = "Email" }) 
    @Html.PasswordFor(x => Model.Password, new { placeholder = "Password" }) 
    <input type="submit" value="SignIn" class="button small-button"> 
} 

참고. 이것은 AJAX를 사용하여 다른 도메인에서 양식을로드하는 동안 주 사이트가 CDN을 사용하여 정적으로 호스팅되기 때문에 수행됩니다. 이것은 쿠키가 AJAX 요청으로 전송되지 않는 것을 제외하고는 작동합니다. 내가 SetWithCredentialsTrue() 메소드가 호출되는 것을 볼 수 있지만

<script type="text/javascript"> 
    function SetWithCredentialsTrue(xhr) { 
     console.log("SetWithCredentialsTrue(xhr)", xhr); 
     xhr.withCredentials = true; 
    } 
</script> 

것은,이 때 HTTP 요청이 발생하는 점에서 작동하지 않는 것 : 나는 OnBegin 이벤트를 사용하여 xhr.withCredentials = true를 설정하여 전송되는 쿠키와이 자바 스크립트를하려고 양식 제출시 쿠키 헤더가 없습니다.

모든 서버 쪽 처리기는 Access-Control-Allow-Credentials 응답 헤더를 trueAccess-Control-Allow-Origin을 주 (정적) 사이트 도메인으로 설정합니다.

UPDATE : 좀 더 콘솔 로깅, 내 OnBegin 이벤트 핸들러 (SetWithCredentialsTrue)에 전달 된 xhr 매개 변수가 XMLHttpRequest 개체에 따라서 영향이없는 그 위에 withCredentials 설정이 아닌 것을 확인했습니다. 그러면 XMLHttpRequest 객체에 어떻게 액세스 할 수 있습니까?

답변

1

나는 마지막으로이 알아 냈어. XMLHttpRequest 객체는 ASP.NET MVC 라이브러리를 통해 노출되지 않습니다.

$(document).on("submit", "form[data-ajax=true]", function (evt) { 
    var clickInfo = $(this).data(data_click) || [], 
     clickTarget = $(this).data(data_target), 
     isCancel = clickTarget && clickTarget.hasClass("cancel"); 
    evt.preventDefault(); 
    if (!isCancel && !validate(this)) { 
     return; 
    } 
    asyncRequest(this, { 
     url: this.action, 
     type: this.method || "GET", 
     data: clickInfo.concat($(this).serializeArray()), 
     xhrFields: { 
      withCredentials: true 
     } 
    }); 
}); 

참고 : xhrFields 내가 추가 한 부분이 참으로 withCredentials을 설정하도록 나는 jquery.unobtrusive-은 ajax.js의 ASP.NET MVC 도우미가 사용하는 JS 라이브러리를 변경 할 수 있었다.

0

당신이하려고하는 것이 무엇인지, AJAX 게시물을 사용하여 한 도메인에서 다른 도메인으로 데이터를 보내시겠습니까?

그렇다면 보안 문제로 인해 브라우저에서 허용하지 않는다고 말씀 드리고 싶습니다.

여전히 원하는 경우 CORS 및 JSONP를 사용하여 두 가지 옵션을 사용할 수 있습니다.

http://csharp-video-tutorials.blogspot.in/2016/09/calling-aspnet-web-api-service-in-cross.html

http://csharp-video-tutorials.blogspot.in/2016/09/cross-origin-resource-sharing-aspnet.html

+0

질문은 한 도메인에서 다른 도메인으로 ASP.NET MVC AJAX 양식을 제출하는 것입니다. 나는 'xhr.withCredentials = true'를 설정하여 JQuery를 사용하여 유사한 요청을 할 수 있지만 ASP.NET MVC Ajax 양식에서 동일한 작업을 수행하려고한다. 그렇지 않으면 CORS가 작동합니다. 양식이 제출되고 쿠키 헤더는 전송되지 않습니다. – Alex