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;
}
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;
}