WebApi返回Xml和返回json处理方法

来源:互联网 发布:本科院校大数据专业 编辑:程序博客网 时间:2024/04/28 03:13

webApi可以返回json、xml和自定义string字符串,本文我们不讨论返回string字符串。

一、全局都只能返回一种类型Xml或者json

1、返回xml,当我们新建一个webapi项目的时候系统默认webapiConfig默认返回xml此时webapiconfig的配置为:

 public static void Register(HttpConfiguration config)        {            // Web API configuration and services            // Web API routes            config.MapHttpAttributeRoutes();            config.Routes.MapHttpRoute(                name: "DefaultApi",                routeTemplate: "api/{controller}/{action}/{id}",                defaults: new { id = RouteParameter.Optional }            );            config.Routes.MapHttpRoute(                name: "Products",                routeTemplate: "api/{controller}/{id}",                defaults: new { id = RouteParameter.Optional }            );}

2、当我们需要返回json的时候整个配置文件变为

 public static class WebApiConfig    {        public static void Register(HttpConfiguration config)        {            // Web API configuration and services            // Web API routes            config.MapHttpAttributeRoutes();            config.Routes.MapHttpRoute(                name: "DefaultApi",                routeTemplate: "api/{controller}/{action}/{id}",                defaults: new { id = RouteParameter.Optional }            );            config.Routes.MapHttpRoute(                name: "Products",                routeTemplate: "api/{controller}/{id}",                defaults: new { id = RouteParameter.Optional }            );            var jsonFormatter = new JsonMediaTypeFormatter();            //optional: set serializer settings here            config.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter));            // 取消注释下面的代码行可对具有 IQueryable 或 IQueryable<T> 返回类型的操作启用查询支持。            // 若要避免处理意外查询或恶意查询,请使用 QueryableAttribute 上的验证设置来验证传入查询。            // 若要在应用程序中禁用跟踪,请注释掉或删除以下代码行            //config.EnableSystemDiagnosticsTracing();        }        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;            }        }    }

二、需要单个方法返回json,则只是需要在某一个方法中添加json方法。如下:

public HttpResponseMessage PostUser(User user) { JavaScriptSerializer serializer = new JavaScriptSerializer(); string str = serializer.Serialize(user); HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") }; return result; } 



封装返回json方法
public static HttpResponseMessage toJson(Object obj) { String str; if (obj is String ||obj is Char) { str = obj.ToString(); } else { JavaScriptSerializer serializer = new JavaScriptSerializer(); str = serializer.Serialize(obj); } HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") }; return result; } 




0 0