.net WebAPI返回xml、json格式

 

WebAPI返回xml、json格式简单示例

using System.Net.Http.Formatting;
public class TestController : ApiController {
       public static List<Student> list = new List<Student>
        { 
            new Student { Name="张三",Age=25,Weight=153.5M },
            new Student { Name="李四",Age=18,Weight=110.5M },
            new Student { Name="王五",Age=23,Weight=126.5M }
        };
        [HttpGet]
        [Route("api/Test/GetDataForXML")]
        public HttpResponseMessage GetDataForXML(string date)
        {
            HttpResponseMessage result = Request.CreateResponse<List<Student>>(HttpStatusCode.OK, list, Configuration.Formatters.XmlFormatter);
            return result;
        }

        [HttpPost]
        [Route("api/Test/PostDataForXML")]
        public HttpResponseMessage PostDataForXML([FromBody]string date)
        {
            HttpResponseMessage result = Request.CreateResponse<List<Student>>(HttpStatusCode.OK, list, Configuration.Formatters.XmlFormatter);
            return result;
        }

        [HttpGet]
        [Route("api/Test/GetDataForJSON")]
        public HttpResponseMessage GetDataForJSON(object date)
        {
            HttpResponseMessage result = Request.CreateResponse<List<Student>>(HttpStatusCode.OK, list, Configuration.Formatters.JsonFormatter);
            return result;
        }
    }
    public class Student
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public decimal Weight { get; set; }
    }
 

 

posted @ 2018-09-26 16:54  听雨的人  阅读(2426)  评论(2编辑  收藏  举报