第一种:
public static void Register(HttpConfiguration config) { //1、将默认的xml格式化程序清除 GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear(); //2、设置默认返回json格式的数据 GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(new QueryStringMapping("dataType","json","application/json")); //3、如果设置http://xxx?dataType=xml,则返回xml格式的数据 GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(new QueryStringMapping("dataType", "xml", "application/xml")); // Web API 配置和服务 // Web API 路由 config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); config.Routes.MapHttpRoute( name: "DefaultApi2", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional } ); } }
Action的使用方式:
[AcceptVerbs("GET", "POST")] [Route("FetchList")] public Resultx FetchList() { return new Resultx { Code = 0, Message = "OK", Result = new { name="list",list=new List<string> { "1","2"} } }; }
第二种:
[AcceptVerbs("GET", "POST")] [Route("FetchList")] //使用IHttpActionResult接口,用JsonResult<>()来返回Json字符串 public IHttpActionResult FetchList() { return Json(new { Code = 0, Message = "OK", Result = new { name = "list", list = new List<string> { "1", "2" } } }); }
以上两种结果都能正常返回Json字符串:
{"Code":0,"Message":"OK","Result":{"name":"list","list":["1","2"]}}