2017-10-24 2 views
0

public class UPWebsiteAPIController : ApiController 전에 [System.Web.Http.Cors.EnableCors(origins: "*", headers: "*", methods: "*")]을 추가했으며 POST 데이터를 원할 때마다 return new JsonResult { Data = toReturn };을 입력해야합니다. 문제는이 기능을 완전히 실행하고 toRerurn 객체를 반환하지만, 브라우저가 없음 액세스 제어 - 출처 Allow 헤더가 요청 자원에 존재ASP.NET MVC에서 CORS 사용

백엔드 오류 코드 500

를 얻을 수있다이다 코드 :

 [System.Web.Http.HttpPost] 
    public async Task<System.Web.Mvc.ActionResult> CreateEvent(FormDataCollection formData) 
    { 
     try 
     { 
      (code which works fine) 
      toReturn[0] = HttpStatusCode.OK; 
      return new JsonResult { Data = toReturn }; 
     } 
     catch (Exception ex) 
     { 
      toReturn[0] = HttpStatusCode.BadRequest; 
      return new JsonResult { Data = toReturn }; 
     } 
    } 

Fronend 코드 :

$.ajax({  
    type: "POST", 
    url: 'http://www.XXX.aspnet.pl/api/UPWebsiteAPI/CreateEvent', 
    data: data, 
    beforeSend: function() { 

     $loading.show(); 

    }, 

    success: function(response) { 
     console.log('sukces'); 
     console.log(response); 

     $loading.hide(); 
     $response.show(); 
     $response.find('.pay-button').show(); 
     $response.find('.pay-link').attr('href', response.Data[1]); 

     $response.find('h2').html("Gratulacje!'); 

    }, 
    error: function(response) { 
     console.log('error'); 
     console.log(response); 
     $loading.hide(); 
     $response.show(); 
     $('.pay-button').hide(); 
     $response.find('h2').html("Przepraszamy..."); 
    } 
    }); 

어떻게해야합니까? 재미있는 점은 때로는 문제없이 작동하고 때로는 (때로는) 그 오류가 발생한다는 것입니다.

답변

1

global.asax.cs 파일에서 아래 방법을 추가하십시오.

protected void Application_BeginRequest(object sender, EventArgs e) 
    { 
     HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*"); 
     if (HttpContext.Current.Request.HttpMethod == "OPTIONS") 
     { 
      HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "POST, PUT, DELETE,GET"); 

      HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "content-type,Access-Control-Allow-Origin,authToken, Accept"); 
      HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000"); 
      HttpContext.Current.Response.End(); 
     } 
    } 
+0

내게 도움이되지 않았다. – Cezar

+0

토큰 기반 인증을 사용하고 있습니까? –