2015-01-28 5 views
0

Web Api 프로젝트 (TestApi 이름)가 있습니다. 나는이 프로젝트를 디버깅 할 때웹 응용 프로그램에서 교차 원점 요청이 차단되었습니다.

, 그리고 내가 JSON 데이터를 얻기하고있어 내가 다른 MVC 프로젝트에서이 API 메서드를 호출 할 "http://localhost:31310/api/Authors"

이제이 URL을 입력 할 때 (이름 : callTestApi) , Jquery 사용하여이 코드 줄을 작성했습니다.

 $.ajax({ 
      type: 'GET', 
      contentType: 'application/json; charset=utf-8', 
      url: 'http://localhost:31310/api/Authors/', 
      success: function (data) { 
       var getAll = data; 
       alert(data[0].Name) 
      }, 
      error: function (data) { 
       alert('Error in getting result'); 
      } 
     }); 

나는 나의 TestApi 프로젝트에 CORS를 사용할 수있다. 내가이 명령을 사용하여, 내 프로젝트 (TestApi)에 CORS를 추가 한

[EnableCors(origins: "http://localhost", headers: "*", methods: "*")] 
    public class AuthorsController : ApiController 
    { 
     private TestWebApiContext db = new TestWebApiContext(); 

     // GET: api/Authors 
     public IQueryable<Author> GetAuthors() 
     { 
      return db.Authors; 
     } 
    } 

여기에서 볼

Install-Package Microsoft.AspNet.WebApi.Cors -Version 5.2.2 

나는이를 추가 할 수

public static void Register(HttpConfiguration config) 
     { 
      // Web API configuration and services 

      // Web API routes 
      config.MapHttpAttributeRoutes(); 

      config.Routes.MapHttpRoute(
       name: "DefaultApi", 
       routeTemplate: "api/{controller}/{id}", 
       defaults: new { id = RouteParameter.Optional } 
      ); 

      config.EnableCors(); 
     } 
+0

와일드 카드 대신 헤더를 나열 해보십시오. – Musa

+0

당신이 얻은 오류는 무엇인지 보여줄 수 있습니까? – Dalorzo

답변

2

시도를 제출 Webapiconfig 수있는 당신의 <System.WebServer> 태그 뒤에있는 API의 web.config

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

config.EnableCors(); 일 수도 있습니다.

0

시도 :
[EnableCors(origins: "*", headers: "*", methods: "*")]
내가 로컬 호스트가이 허용되지 않습니다 생각합니다.

관련 문제