差分

ナビゲーションに移動 検索に移動

JsonResult クラス (System.Web.Mvc)

1,632 バイト追加, 2012年5月14日 (月) 08:00
編集の要約なし
// いるので、そいつを使った方がシンプルではある。
// return this.Json(obj, JsonRequestBehavior.AllowGet);
}
}
</source>
 
== 似たような実装例 ==
JsonRequestBehavior.AllowGetが面倒なので[[DynamicJson]]で実装してみた。
とくに意味はない。
 
なんかよくわからないけど、[[契約による設計]]([[System.Diagnostics.Contracts 名前空間]])を使ってみたかった。
とくに意味はない。
 
<source lang="csharp">
using System;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Diagnostics.Contracts;
using Codeplex.Data;// DynamicJson
 
public class JsonResult2 : ActionResult
{
public static readonly string ContentTypeDefault = "application/json";
 
public string ContentType { get; set; }
public Encoding ContentEncoding { get; set; }
public object Data { get; set; }
 
public JsonResult2()
{
}
 
public JsonResult2(object data)
{
this.ContentEncoding = null;
this.Data = data;
}
 
public override void ExecuteResult(ControllerContext context)
{
// 契約による設計:事前条件
Contract.Requires(context != null);
 
// 実装
HttpResponseBase response = context.HttpContext.Response;
if (string.IsNullOrEmpty(this.ContentType))
{
response.ContentType = ContentTypeDefault;
}
else
{
response.ContentType = this.ContentType;
}
 
if (this.ContentEncoding != null)
{
response.ContentEncoding = this.ContentEncoding;
}
 
// DynamicJSONでシリアライズ
string json = DynamicJson.Serialize(this.Data);
response.Output.Write(json);
}
}
匿名利用者

案内メニュー