2014-07-24 3 views
1

에서 컨트롤러를 찾을 수 없습니다 반환, 나는 다음 단계에 따라 CORS를 활성화 :프리 플라이트 요청 (404) 나는 WebAPI 프로젝트가있는 영역

  1. 는 nuget 패키지를 가져옵니다 : Install-Package Microsoft.AspNet.WebApi.Cors.
  2. WebApiConfig.cs에 config.EnableCors();이 추가되었습니다.
  3. 컨트롤러에 [EnableCors(origins: "*", headers: "*", methods: "*")]을 추가했습니다.

컨트롤러는 루트의 Controllers 폴더와 영역 내에 있습니다.

/Controllers/ValuesController 
/Areas/TestArea/Controllers/OtherStuffController 

두 컨트롤러는 [EnableCors(...)] 속성을 가지고있다.

제 문제는 ValuesController입니다.

Fiddler를 사용하여 OtherStuffController에 대한 요청을 검사 한 결과 클라이언트가 프리 플라이트 OPTIONS 요청을 보냈지 만 서버가 200 OK 대신 404를 찾지 못했지만 ValuesController이 완벽하게 작동 함을 알 수 있습니다.

내가 뭘 잘못하고 있니? TestArea 영역의 컨트롤러가 CORS 요청과 함께 작동하지 않는 이유는 무엇입니까?

이름 이외의 두 컨트롤러와 영역에 다른 것은 없습니다.

추가 정보

경로 :

http://localhxst:57578/values 
http://localhxst:57578/testarea/otherstuff 

값 요청 (작업) :

(REQUEST) 
OPTIONS http://localhost:57578/values HTTP/1.1 
Host: localhost:57578 
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; rv:31.0) Gecko/20100101 Firefox/31.0 
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 
Accept-Language: en-gb,en;q=0.5 
Accept-Encoding: gzip, deflate 
Origin: http://localhxst:12345 
Access-Control-Request-Method: GET 
Access-Control-Request-Headers: authorization 
Connection: keep-alive 

(RESPONSE) 
HTTP/1.1 200 OK 
Cache-Control: no-cache 
Pragma: no-cache 
Expires: -1 
Server: Microsoft-IIS/8.0 
Access-Control-Allow-Origin: * 
Access-Control-Allow-Headers: authorization 
X-AspNet-Version: 4.0.30319 
X-SourceFiles: =?UTF-8?B?QzpcVXNlcnNcYmVuLmdvbGRlblxEb2N1bWVudHNcV29ya1xWb2ljZVNpbXBsaWZpZWRcQVBJXFZvaWNlU2ltcGxpZmllZC5QdWJsaWNBUElcdmFsdWVz?= 
X-Powered-By: ASP.NET 
Date: Thu, 24 Jul 2014 20:12:56 GMT 
Content-Length: 0 

// In WebApiConfig.cs 
config.Routes.MapHttpRoute("DefaultApi", "{controller}/{id}", 
    new {id = RouteParameter.Optional}); 

// In Areas/TestArea/TestAreaAreaRegistration.cs 
context.MapRoute("TestArea_default","TestArea/{controller}/{id}", 
    new {id = UrlParameter.Optional}); 

URL을 나는 액션 메소드에 액세스하는 데 사용하고 있습니다,

의해 따랐다

(REQUEST) 
GET http://localhxst:57578/values HTTP/1.1 
Host: localhost:57578 
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; rv:31.0) Gecko/20100101 Firefox/31.0 
Accept: application/json 
Accept-Language: en-gb,en;q=0.5 
Accept-Encoding: gzip, deflate 
Authorization: Bearer HQkpyzeQ5NM1Va1Ow__6N6JzuRdMweDIJDneDQer1tL1uMhkrG4gsRYkXLQ1F4782L5vDTMOkoqvOEtO753n6TJ2BU-KNaxdXRAtf336c-r8MXMi_nWliw1vT1Xa7Wmt3eV5b9HmJR4Bnmt4gTavtoC0qwQVsoX_miV_VanJ98j_aaoNdNNZcnN5FsJ2eoLx7UebBDxXBMFmXEtOUTtWCsRp-g26mwKjbK3HeDoiUU2Ivh-VleUVImdh9ASwInbZ 
Referer: http://localhxst:12345/ 
Origin: http://localhxst:12345 
Connection: keep-alive  

(RESPONSE) 
HTTP/1.1 200 OK 
Cache-Control: no-cache 
Pragma: no-cache 
Content-Type: application/json; charset=utf-8 
Expires: -1 
Server: Microsoft-IIS/8.0 
Access-Control-Allow-Origin: * 
X-AspNet-Version: 4.0.30319 
X-SourceFiles: =?UTF-8?B?QzpcVXNlcnNcYmVuLmdvbGRlblxEb2N1bWVudHNcV29ya1xWb2ljZVNpbXBsaWZpZWRcQVBJXFZvaWNlU2ltcGxpZmllZC5QdWJsaWNBUElcdmFsdWVz?= 
X-Powered-By: ASP.NET 
Date: Thu, 24 Jul 2014 20:12:56 GMT 
Content-Length: 13 

["ABC","DEF"] 

OtherStuff 요청 (PRELIGHT 실패)

(REQUEST) 
OPTIONS http://localhxst:57578/testarea/otherstuff HTTP/1.1 
Host: localhost:57578 
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; rv:31.0) Gecko/20100101 Firefox/31.0 
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 
Accept-Language: en-gb,en;q=0.5 
Accept-Encoding: gzip, deflate 
Origin: http://localhost:12345 
Access-Control-Request-Method: GET 
Access-Control-Request-Headers: authorization 
Connection: keep-alive 

(RESPONSE) 
HTTP/1.1 404 Not Found 
Cache-Control: private 
Content-Type: text/html; charset=utf-8 
Server: Microsoft-IIS/8.0 
X-AspNet-Version: 4.0.30319 
X-SourceFiles: =?UTF-8?B?QzpcVXNlcnNcYmVuLmdvbGRlblxEb2N1bWVudHNcV29ya1xWb2ljZVNpbXBsaWZpZWRcQVBJXFZvaWNlU2ltcGxpZmllZC5QdWJsaWNBUElcdGVzdGFyZWFcb3RoZXJzdHVmZg==?= 
X-Powered-By: ASP.NET 
Date: Thu, 24 Jul 2014 20:35:08 GMT 
Content-Length: 3194 
<!DOCTYPE html> 
<html> 
    <head> 
     <title>The resource cannot be found.</title> 
     <meta name="viewport" content="width=device-width" /> 
     <style> 
     body {font-family:"Verdana";font-weight:normal;font-size: .7em;color:black;} 
     p {font-family:"Verdana";font-weight:normal;color:black;margin-top: -5px} 
     b {font-family:"Verdana";font-weight:bold;color:black;margin-top: -5px} 
     H1 { font-family:"Verdana";font-weight:normal;font-size:18pt;color:red } 
     H2 { font-family:"Verdana";font-weight:normal;font-size:14pt;color:maroon } 
     pre {font-family:"Consolas","Lucida Console",Monospace;font-size:11pt;margin:0;padding:0.5em;line-height:14pt} 
     .marker {font-weight: bold; color: black;text-decoration: none;} 
     .version {color: gray;} 
     .error {margin-bottom: 10px;} 
     .expandable { text-decoration:underline; font-weight:bold; color:navy; cursor:hand; } 
     @media screen and (max-width: 639px) { 
      pre { width: 440px; overflow: auto; white-space: pre-wrap; word-wrap: break-word; } 
     } 
     @media screen and (max-width: 479px) { 
      pre { width: 280px; } 
     } 
     </style> 
    </head> 

    <body bgcolor="white"> 

      <span><H1>Server Error in '/' Application.<hr width=100% size=1 color=silver></H1> 

      <h2> <i>The resource cannot be found.</i> </h2></span> 

      <font face="Arial, Helvetica, Geneva, SunSans-Regular, sans-serif "> 

      <b> Description: </b>HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. &nbsp;Please review the following URL and make sure that it is spelled correctly. 
      <br><br> 

      <b> Requested URL: </b>/testarea/otherstuff<br><br> 

      <hr width=100% size=1 color=silver> 

      <b>Version Information:</b>&nbsp;Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.34009 

      </font> 

    </body> 
</html> 
<!-- 
[HttpException]: The controller for path &#39;/testarea/otherstuff&#39; was not found or does not implement IController. 
    at System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) 
    at System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName) 
    at System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory) 
    at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) 
    at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) 
    at System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) 
    at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() 
    at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) 
--> 

ValuesController.cs

namespace MyAPIApp.PublicAPI.Controllers 
{ 

    [EnableCors(origins: "*", headers: "*", methods: "*")] 
    [Authorize] 
    public class ValuesController : ApiController 
    { 
     private static readonly List<string> values = new List<string> { "ABC", "DEF" }; 

     public IEnumerable<string> Get() { return values; } 
    } 
} 

OtherStuffController.cs

0
+0

당신이 쿼리하려고하는 URI를 게시 할 수 있습니까? – Machinarius

+0

라우팅 구성이 도움이됩니다. – Dalorzo

+0

@Machinarius : 추가 정보가 추가되었습니다. – BG100

답변

4

문제점을 발견했습니다. 당신이 추가> 지역 상황에 맞는 메뉴를 통해 프로젝트의 영역을 만들 때

이, 비주얼 스튜디오는 다음과 같은 코드를 사용하여 AreaRegistration 템플릿으로 영역을 생성합니다 그러나

public override void RegisterArea(AreaRegistrationContext context) { 
    context.MapRoute(
     "TestArea_default", 
     "TestArea/{controller}/{id}", 
     new {id = UrlParameter.Optional} 
     ); 
} 

을,이 코드는 ApiControllers에 대한 정확하지 않습니다 .올바른 경로 등록 코드는 다음과 같습니다

public override void RegisterArea(AreaRegistrationContext context) { 

    context.Routes.MapHttpRoute(
     "TestArea_default", 
     "TestArea/{controller}/{id}", 
     new { id = RouteParameter.Optional }); 
} 

그것은이 CORS와는 아무 상관 없었다 밝혀졌습니다.

관련 문제