服务端
1. 创建Web.API应用程序
2 创建一个demo
[RoutePrefix("api/test")] public class TestController : ApiController { [HttpGet] [Route("testGet")] public string TestGet() { return "Hello, I‘m a get method"; } }
3 返回的数据内容格式为:
4 此时返回的是xml格式, 如果想返回json格式, 有两种方法:
方法一:
在Global的Application_Start方法中添加配置:
GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
结果如下:
方法二:
. 添加新的类JsonContentNegotiator.cs
public class JsonContentNegotiator : IContentNegotiator { private readonly JsonMediaTypeFormatter _jsonFormatter; public JsonContentNegotiator(JsonMediaTypeFormatter formatter) { _jsonFormatter = formatter; } public ContentNegotiationResult Negotiate(Type type, HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters) { var result = new ContentNegotiationResult(_jsonFormatter, new MediaTypeHeaderValue("application/json")); return result; } }
. 在WebApiConfig的Register方法添加配置
var jsonFormatter = new JsonMediaTypeFormatter(); config.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter));
结果如下:
客户端:
ajax或http请求