web api寫api接口時默認返回的是把你的對象序列化後以XML形式返回,那麼怎樣才能讓其返回爲json呢,下面就介紹兩種方法: web
方法一:改配置法
找到Global.asax文件,在Application_Start()方法中添加一句:
代碼以下:
GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
修改後:
代碼以下:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
// 使api返回爲json
GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
}
這樣返回的結果就都是json類型了,但有個很差的地方,若是返回的結果是String類型,如123,返回的json就會變成"123";
解決的方法是自定義返回類型(返回類型爲HttpResponseMessage)
代碼以下:
public HttpResponseMessage PostUserName(User user)
{
String userName = user.userName;
HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(userName,Encoding.GetEncoding("UTF-8"), "application/json") };
return result;
}
方法二:萬金油法
方法一中又要改配置,又要處理返回值爲String類型的json,甚是麻煩,不如就不用web api中的的自動序列化對象,本身序列化後再返回
代碼以下:
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;
}
方法三:最麻煩的方法
方法一最簡單,但殺傷力太大,全部的返回的xml格式都會被斃掉,那麼方法三就能夠只讓api接口中斃掉xml,返回json
先寫一個處理返回的類:
代碼以下:
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;
}
}
找到App_Start中的WebApiConfig.cs文件,打開找到Register(HttpConfiguration config)方法
添加如下代碼:
代碼以下:
var jsonFormatter = new JsonMediaTypeFormatter();
config.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter));
添加後代碼以下:
代碼以下:
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
var jsonFormatter = new JsonMediaTypeFormatter();
config.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter));
}
方法三若是返回的結果是String類型,如123,返回的json就會變成"123",解決方法同方法一。
其實web api會自動把返回的對象轉爲xml和json兩種格式並存的形式,方法一與方法三是斃掉了xml的返回,而方法二是自定義返回。