2016-06-26 2 views
0

내가 데이터와 코드를 반환 내가 웹 API 컨트롤러가 MVC5 일하고

[Route("m/api/Group")] 
     [HttpGet] 
     public IHttpActionResult ListOfGroups() 
     { 
      try 
      { 
       var listOfGroups = GroupExecutor.GetListOfGroups(); 
       return Ok(listOfGroups); 
      } 
      catch (Exception ex) 
      { 
       LogClass.Logger.Error(ex.Message, ex); 
       return InternalServerError(); 
      } 
     } 

다음과 같다 . 이 코드를 실행하면 이제 API 메소드로 이동

[HttpPost] 
     [ValidateAntiForgeryHeader] 
     public ActionResult GetListOfGroups() 
     { 
      try 
      { 
       var listofGroups = new GroupController().ListOfGroups(); 
       return GetJsonContentResult(listofGroups); 
      } 
      catch (Exception ex) 
      { 
       LogClass.Logger.Error(ex.Message, ex); 
       return new HttpStatusCodeResult(HttpStatusCode.InternalServerError, Utility.GetDescriptionFromEnumValue(Helper.TypeOfError.ErrorOccuredWhileProcessingRequest)); 
      } 
     } 

아래로하지만, 그주는 오류 다시 컨트롤러로 돌아 왔을 때

는 지금은 MVC 컨트롤러 코드를 통해 동일한 프로젝트 내에서이 API 컨트롤러 방법을 소비 할 것입니다

Error getting value from 'Content Negotiation' on 'System.Web.Http.Results.OkNegotiatedContentResult 

이 문제를 어떻게 해결할 수 있습니까?

EDIT : 여기

public ContentResult GetJsonContentResult(object data) 
     { 
      var camelCaseFormatter = new JsonSerializerSettings(); 
      camelCaseFormatter.ContractResolver = new CamelCasePropertyNamesContractResolver(); 
      var jsonResult = new ContentResult 
      { 
       Content = JsonConvert.SerializeObject(data, camelCaseFormatter), 
       ContentType = "application/json" 
      }; 
      return jsonResult; 
     } 
+0

왜 내가 컨트롤러에서 이와 같은 웹 API를 호출해야하는지 모르겠습니까? – dotnetstep

+0

MVC5에서 API 컨트롤러를 직접 호출하기 때문에 클라이언트를 만들 필요가 없습니다. – Mahajan344

+0

GetJsonContentResult 메서드는 무엇을합니까? – dotnetstep

답변

0
var controller = new MyAPIController(); 
var content = controller.GetMyAPIMethod(someParam); 
      var myModel = ((OkNegotiatedContentResult<MyObjectType>)(content.Result)).Content; 

MyAPIController은 UR API 컨트롤러는 GetMyAPIMethod UR의 API 메소드이고 MyObjectType는 리턴되는 데이터 타입이다. 컨트롤러에서 이것을 사용하면 정상적으로 동작합니다.

1

웹 API가 항상 결과를 반환하기를 바랍니다.

나는 그것이 항상 곁에
Ok(yourdata) 

는 이제 GetJsonContentResult 방법이 방법은 다음과 같은 수정해야한다고 가정합니다. 이 WebAPI에서 OkNegotiatedContentResult를 반환하면 Content 속성을 읽어야합니다. 내가 반성하면서 그랬다. (다른 방법이 있습니다).

public ContentResult GetJsonContentResult(object data) 
     {    
      var camelCaseFormatter = new JsonSerializerSettings(); 
      camelCaseFormatter.ContractResolver = new CamelCasePropertyNamesContractResolver(); 
      PropertyInfo pinfo = data.GetType().GetProperty("Content");    
      var jsonResult = new ContentResult 
      { 

       Content = JsonConvert.SerializeObject(pinfo.GetValue(data) , camelCaseFormatter), 
       ContentType = "application/json" 
      }; 
      return jsonResult; 
     } 
관련 문제