Я обнаружил, что создание нового JsonResult
и возвращение неудовлетворительного - замена всех вызовов на возвращает Json (obj)
с возвратом нового MyJsonResult {Data = obj}
- боль.
Итак, я понял, почему бы не просто захватить JsonResult
с помощью ActionFilter
: [ ! d14]
public class JsonNetFilterAttribute: ActionFilterAttribute {public override void OnActionExecuted (ActionExecutedContext filterContext) {if (filterContext.Result - JsonResult == false) {return; } filterContext.Result = новый фильтр JsonNetResult ((JsonResult )Context.Result); } private class JsonNetResult: JsonResult {public JsonNetResult (JsonResult jsonResult) {this.ContentEncoding = jsonResult.ContentEncoding; this.ContentType = jsonResult.ContentType; this.Data = jsonResult.Data; this.JsonRequestBehavior = jsonResult.JsonRequestBehavior; this.MaxJsonLength = jsonResult.MaxJsonLength; this.RecursionLimit = jsonResult.RecursionLimit; } public override void ExecuteResult (Контекст ControllerContext) {if (context == null) {throw new ArgumentNullException ("context"); } var isMethodGet = string.Equals (context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase); if (this.JsonRequestBehavior == JsonRequestBehavior.DenyGet & amp; isMethodGet) {throw new InvalidOperationException ("GET не разрешено! Изменить JsonRequestBehavior для AllowGet."); } var response = context.HttpContext.Response; response.ContentType = string.IsNullOrEmpty (this.ContentType)? "application / json": this.ContentType; if (this.ContentEncoding! = null) {response.ContentEncoding = this.ContentEncoding; } if (this.Data! = null) {response.Write (JsonConvert.SerializeObject (this.Data)); }}}}
Это может быть применено к любому методу, возвращающему JsonResult
вместо JSON.Net:
[JsonNetFilter] public ActionResult GetJson () {return Json (new {hello = new Date (2015, 03, 09)}, JsonRequestBehavior.AllowGet)}
, который будет отвечать [ ! d16]
{"hello": "2015-03-09T00: 00: 00 + 00: 00"}
по желанию!
Вы можете, если не возражать, что сравнивает
при каждом запросе, добавьте это в свой FilterConfig
:
// ... filters.Add (новый JsonNetFilterAttribute ());
, и все ваши JSON теперь будут сериализованы с помощью JSON.Net вместо встроенного JavaScript-скрипта
.