我使用ASP.NET Web API调用并显示java Web服务。我如何做到这一点,当我运行我的ASP.NET Web API时,页面显示JSON数据而不是HTML?
以下是我的代码:
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
public class DemoController : Controller
{
private DemoRestfulClient demoRestfulClient = new DemoRestfulClient();
public ActionResult Index()
{
var Result1 = demoRestfulClient.AdditionJava2().Result;
return Content(Result1);
}
}
有人请帮助我。非常感谢你。
答案 0 :(得分: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中单独查看内容。
通过使用ajax,您可以单独获取json对象的内容。
例如,
$.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对象视为**msg**
。
数据将包含已解析的json对象,您可以按数据获取必要的数据。 yourFieldName
希望这对你有所帮助! :)