「JsonResult クラス (System.Web.Mvc)」の版間の差分
imported>Administrator |
imported>Administrator 細編集の要約なし |
||
| 29行目: | 29行目: | ||
// いるので、そいつを使った方がシンプルではある。 | // いるので、そいつを使った方がシンプルではある。 | ||
// return this.Json(obj, JsonRequestBehavior.AllowGet); | // 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); | |||
} | } | ||
} | } | ||