2017-10-12 3 views
0

ASP.NET 웹 API를 사용하여 Java 웹 서비스를 호출하고 표시하고 있습니다. 어떻게하면 ASP.NET 웹 API를 실행할 때 HTML 대신 JSON 데이터가 표시되도록 할 수 있습니까? 결과가 HTML 대신 JSON으로 반환됩니다.

public class DemoController : Controller 
{ 
    private DemoRestfulClient demoRestfulClient = new DemoRestfulClient(); 
    public ActionResult Index() 
    { 
     var Result1 = demoRestfulClient.AdditionJava2().Result; 
     return Content(Result1); 
    } 
} 

누군가가 저를 도와주세요

DemoRestfulClient.cs

public class DemoRestfulClient 
{ 
    private string BASE_URL = "http://localhost:8080/"; 
    public Task<string> AdditionJava2() 
    { 
     { 
      try 
      { 
       var client = new HttpClient(); 
       client.BaseAddress = new Uri(BASE_URL); 
       client.DefaultRequestHeaders.Accept.Add(
        new MediaTypeWithQualityHeaderValue("application/json")); 
       HttpResponseMessage response = client.GetAsync("AdditionJava2").Result; 
       return response.Content.ReadAsStringAsync(); 
      } 

      catch (Exception e) 
      { 
       HttpContext.Current.Server.Transfer("ErrorPage.html"); 
      } 

      return null; 
     } 
    } 
} 

DemoController.cs

: 여기

내 코드입니다. 미리 감사드립니다.

답변

0
public class DemoController : Controller 
{ 
    private DemoRestfulClient demoRestfulClient = new DemoRestfulClient(); 
    public ActionResult Index() 
    { 
     var Result1 = demoRestfulClient.AdditionJava2().Result; 
     return Json(Result1); 
    } 
} 

위의 메서드는 json 개체를 반환합니다. json 개체를 얻고 싶습니다. :)

json에서 콘텐츠를 개별적으로 보려면 Json 개체를 구문 분석해야합니다.

아약스를 사용하면 json 개체의 콘텐츠를 별도로 가져올 수 있습니다. 예를 들어

성공 (MSG)에서

         $.ajax({ 
              url: $("#head").val() + "/Template/updatedTmpltView", 
              dataType: "html", 
              data: {}, 
              type: "POST", 
              success: function (msg) { 
               data = $.parseJSON(msg) 
               var name = data.FieldName; 
               var type = data.FieldType; 
               var id = data.FieldId; 
              }, 
              error: function (XMLHttpRequest, textStatus, errorThrown) { 
              } 
             }); 

, 당신은 **msg**로 JSON 개체를 얻을.

데이터는 구문 분석 JSON 객체를 포함하고 데이터에서 필요한 데이터를 얻을 수 있습니다. yourFieldName

희망이 도움이되었습니다. :)

+0

안녕하세요, 도와 주셔서 너무 감사드립니다. 나는 아직도 AJAX 부분을 확신하지 못한다. u도 자바 코드를 보여 주면 좀 더 나를 도울 수 있을까요? –

관련 문제