Tôi thêm câu trả lời này đơn giản chỉ vì tôi đang sử dụng giải pháp thay thế không yêu cầu ghi đè lớp System.Web.Mvc.Controller. Tôi thêm các phương thức mở rộng sau vào lớp System.Web.Mvc.Controller. "Lợi ích" duy nhất của giải pháp này là nó không yêu cầu bạn phải thay đổi lớp cơ sở của mã tạo ra các lớp Controller. Nếu không, nó có chức năng tương đương với câu trả lời được chấp nhận.
public static JsonResult ToJsonResult(this Controller controller,
object target,
string contentType,
Encoding contentEncoding,
JsonRequestBehavior behavior)
{
if (target != null)
{
if (target.GetType().HasAttribute<DataContractAttribute>())
{
return new DataContractJsonResult() { ContentType = contentType, ContentEncoding = contentEncoding, JsonRequestBehavior = behavior, Data = target };
}
}
return new JsonResult() { ContentType = contentType, ContentEncoding = contentEncoding, JsonRequestBehavior = behavior, Data = target };
}
public static JsonResult ToJsonResult(this Controller controller, object target)
{
return controller.ToJsonResult(target, null, null, JsonRequestBehavior.DenyGet);
}
public static JsonResult ToJsonResult(this Controller controller, object target, string contentType)
{
return controller.ToJsonResult(target, contentType, null, JsonRequestBehavior.DenyGet);
}
public static JsonResult ToJsonResult(this Controller controller, object target, string contentType, Encoding contentEncoding)
{
return controller.ToJsonResult(target, contentType, contentEncoding, JsonRequestBehavior.DenyGet);
}
public static JsonResult ToJsonResult(this Controller controller, object target, string contentType, JsonRequestBehavior behavior)
{
return controller.ToJsonResult(target, contentType, null, behavior);
}
Trong ứng dụng của mình, tôi ghi đè trình điều khiển mặc định và sử dụng bộ nối tiếp JSON.NET nếu loại có thuộc tính DataContract. Chức năng này được đóng gói trong lớp DataContractJsonResult, không được bao gồm, nhưng được mô hình hóa sau lớp trong câu trả lời được chấp nhận cho câu hỏi này.
liên quan: http://stackoverflow.com/questions/7109967/using-json-net-as-default-json-serializer-in-asp-net-mvc-3-is-it-possible –
Tôi đã hỏi điều này câu hỏi 2 tuần trước khi liên kết trùng lặp ... Điều đó làm cho câu hỏi khác trùng lặp! – Tim