//方法一:直接返回序列化后的json文件
public static HttpResponseMessage ConvertToJson(this Object obj)
{
String str="";
if (obj is String || obj is Char)
{
str = obj.ToString();
}
else
{
string json = Newtonsoft.Json.JsonConvert.SerializeObject(obj);
}
HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };
return result;
}
//方法二:global.asax.cs文件中加上
HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };
方式一:
//Global.asax文件中配置返回xml/json
protected void Application_Start()
{
// 配置返回数据类型
// config.Formatters.Remove(config.Formatters.JsonFormatter);
//移除xml序列化器
GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
//移除json序列化器
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SupportedMediaTypes.Clear();
}
方式二:
//WebApiConfig中配置返回json/xml
public static void Register(HttpConfiguration config)
{
// 配置返回数据类型
//移除json序列化器
config.Formatters.Remove(config.Formatters.JsonFormatter);
//移除xml序列化器
config.Formatters.Remove(config.Formatters.XmlFormatter);
// 配置action调用
config.Routes.MapHttpRoute(
name: "DetApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}