.Net MVC 4 Web Apiに基づくJson形式の出力例

4091 ワード

本文の実例は述べた.NetはMVC 4 Web Apiに基づいてJson形式を出力する方法で、参考にしてください.具体的な実現方法は以下の通りである.
1、Globalにjson出力を追加

   GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(new QueryStringMapping("json", "true", "application/json")); 
   
  

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    // json   http://xxx/api/action?json=true
    GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(new QueryStringMapping("json", "true", "application/json"));
    WebApiConfig.Register(GlobalConfiguration.Configuration);
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
}


2、Globalでのxml解析の削除

   GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear(); 
   
  

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    WebApiConfig.Register(GlobalConfiguration.Configuration);
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
    // xml string string json
    GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
}


3、戻りフォーマットの指定
新規メソッドにはプログラムセットが必要です.

   System.Web.Extensions 
  
public static HttpResponseMessage ToJson(Object obj)
{
    String str;
    if (obj is String || obj is Char)
    {
        str = obj.ToString();
    }
    else
    {
        var serializer = new JavaScriptSerializer();
        str = serializer.Serialize(obj);
    }
    var result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };
    return result;
}

ユーザメソッドをjsonオブジェクト出力に変換

   public HttpResponseMessage GetString(string name) 
  
{
     return ToJson(name);
}

4、デフォルト実装クラスを書き換えるすべての出力はjsonに再解析される
新しいJsonContentNegotiatorクラス

   public class JsonContentNegotiator : IContentNegotiator 
  
{
    private readonly JsonMediaTypeFormatter _jsonFormatter;
    public JsonContentNegotiator(JsonMediaTypeFormatter formatter)
    {
        _jsonFormatter = formatter;
    }

    public ContentNegotiationResult Negotiate(Type type, HttpRequestMessage request, IEnumerable formatters)
    {
        var result = new ContentNegotiationResult(_jsonFormatter, new MediaTypeHeaderValue("application/json"));
        return result;
    }
}


WebApiConfigでの書き換えの使用

   public static void Register(HttpConfiguration config) 
  
{
    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );

    var jsonFormatter = new JsonMediaTypeFormatter();
    config.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter));

    // IQueryable IQueryable
    // , QueryableAttribute 。
    // , http://go.microsoft.com/fwlink/?LinkId=279712。
    //config.EnableQuerySupport();

    // ,
    // , : http://www.asp.net/web-api
    config.EnableSystemDiagnosticsTracing();
}


皆さんのaspについてお話ししたいと思います.Netプログラミングが役立ちます.