一般 WebApi 是根据客户端请求 类型进行对应的返回格式
function getAll() {
$.ajax({
url: "http://localhost:37980/api/Test/Show/3",
type: 'GET',
dataType: "json",
success: function (data) {
var s = "";
$.each(data, function (i, val) {
s += val.Name;
});
$("#modes").html(s);
}
}).fail(
function (xhr, textStatus, err) {
alert('Error: ' + err);
});
}
就会返回 json格式
如果想固定请求成json格式
在TestController.cs
[HttpGet]
public HttpResponseMessage Show(int id)
{
Test p = TestBLL.GeTest(id);
return ToJson(JsonConvert.SerializeObject(p));
}
private HttpResponseMessage ToJson(string jsonData)
{
HttpResponseMessage result = new HttpResponseMessage
{
Content = new StringContent(jsonData, Encoding.GetEncoding("UTF-8"), "application/json")
};
return result;
}