MVC AOP解决JsonResult返回json时间格式

时间:2022-05-30 03:37:02

新建JsonNetResult类:JsonResult

public class JsonNetResult: JsonResult
{
public JsonNetResult()
{
Settings = new JsonSerializerSettings
{
ReferenceLoopHandling=ReferenceLoopHandling.Ignore,
DateFormatString= "yyyy-MM-dd HH:mm:ss",
ContractResolver=new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()//json中属性开头字母小写的驼峰命名
};
}
public JsonSerializerSettings Settings { get; private set; } public override void ExecuteResult(ControllerContext context)
{
if (context == null)
throw new ArgumentNullException("context");
//不允许GET请求
if (this.JsonRequestBehavior == JsonRequestBehavior.DenyGet
&& string.Equals(context.HttpContext.Request.HttpMethod, "GET",
StringComparison.OrdinalIgnoreCase))
throw new InvalidOperationException("JSON GET is not allowed"); HttpResponseBase 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)
return;
var scriptSerializer = JsonSerializer.Create(this.Settings);
scriptSerializer.Serialize(response.Output, this.Data);
}
}

  新建JsonNetActionFilter过滤器:

public class JsonNetActionFilter: IActionFilter
{
public void OnActionExecuted(ActionExecutedContext filterContext)
{
if (filterContext.Result is JsonResult
&& !(filterContext.Result is JsonNetResult))
{
JsonResult jsonResult = (JsonResult)filterContext.Result;
JsonNetResult jsonNetResult = new JsonNetResult(); jsonNetResult.ContentEncoding = jsonResult.ContentEncoding;
jsonNetResult.ContentType = jsonResult.ContentType;
jsonNetResult.Data = jsonResult.Data;
jsonNetResult.JsonRequestBehavior = jsonResult.JsonRequestBehavior;
jsonNetResult.MaxJsonLength = jsonResult.MaxJsonLength;
jsonNetResult.RecursionLimit = jsonResult.RecursionLimit; filterContext.Result = jsonNetResult;
}
} public void OnActionExecuting(ActionExecutingContext filterContext)
{ }
}

  在Global中添加

 GlobalFilters.Filters.Add(new JsonNetActionFilter());

  控制器:

     [HttpGet]
public ActionResult TestJson()
{
return View();
}
[HttpPost]
public ActionResult TestJson(FormCollection fc)
{
Dog dog = new Dog()
{
BirthDay = DateTime.Now,
Id = 5,
Name = "旺财"
};
return Json(dog);
//return new JsonNetResult() { Data = dog };
}

  前端:

    <script type="text/javascript">
$(function () {
$("#btn1").click(function () {
$.ajax({
url: "/Home/TestJson",
dataType: "json",
type: "post",
success: function (data) {
alert(data.name);
alert(data.birthDay);
},
error: function () {
alert("ajax错误");
}
});
});
});
</script>