C#web api戻りタイプをjsonに設定
3805 ワード
Web apiがapiインタフェースを書くときにデフォルトで返すのは、オブジェクトをシーケンス化してXML形式で返すことです.では、jsonに戻すにはどうすればいいのでしょうか.次の2つの方法を紹介します.
方法一:(改配置法)
Globalを見つけたasaxファイル、Application_Start()メソッドに次の文を追加します.
変更後:
このように返される結果はすべてjsonタイプですが、悪いところがあり、返される結果がStringタイプであれば123のように、返されるjsonは「123」になります.
解決策は、カスタム戻りタイプ(戻りタイプはHttpResponseMessage)
方法二:(万金油法)
メソッド1では構成を変更したり、戻り値がStringタイプのjsonを処理したりするのは面倒ですが、web apiの自動シーケンス化オブジェクトを使わずに、自分でシーケンス化してから戻ります
方法2は私がお勧めする方法で、インタフェースごとにそのいくつかのコードを繰り返し書かないために、1つの方法にカプセル化して使用すると便利です.
方法3:(最も面倒な方法)
方法1は最も簡単で、しかし殺傷力が大きすぎて、すべての戻るxmlフォーマットはすべて殺されて、それでは方法3はapiインタフェースの中でxmlを殺すだけで、jsonを返すことができます
処理で返されるクラスを先に書きます.
Appが見つかりましたスタート中のWebApiConfig.csファイル、開くRegister(HttpConfiguration config)メソッドを見つける
次のコードを追加します.
追加後のコードは次のとおりです.
メソッド3戻り結果がStringタイプである場合,123のように戻りjsonは「123」となり,解決方法は同じである.
実はweb apiは自動的に戻ったオブジェクトをxmlとjsonの2つのフォーマットが併存する形式に変えて、方法の1つと方法の3つはxmlの返しを殺して、方法の2つはカスタムの返しです.
方法一:(改配置法)
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;
}
方法二:(万金油法)
メソッド1では構成を変更したり、戻り値が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;
}
方法2は私がお勧めする方法で、インタフェースごとにそのいくつかのコードを繰り返し書かないために、1つの方法にカプセル化して使用すると便利です.
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;
}
方法3:(最も面倒な方法)
方法1は最も簡単で、しかし殺傷力が大きすぎて、すべての戻るxmlフォーマットはすべて殺されて、それでは方法3は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が見つかりましたスタート中の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));
}
メソッド3戻り結果がStringタイプである場合,123のように戻りjsonは「123」となり,解決方法は同じである.
実はweb apiは自動的に戻ったオブジェクトをxmlとjsonの2つのフォーマットが併存する形式に変えて、方法の1つと方法の3つはxmlの返しを殺して、方法の2つはカスタムの返しです.