Setting the default JSON serializer in ASP.NET MVC
In ASP.Net MVC4 the default JavaScript serializer which is used in the JsonResult
class is still the JavaScriptSerializer (you can check it in the code)
I think you have confused it with the ASP.Net Web.API where JSON.Net is the default JS serializer but MVC4 doesn't use it.
So you need to configure JSON.Net to work with MVC4 (basically you need to create your own JsonNetResult
), there are plenty of articles about it:
- ASP.NET MVC and Json.NET
- Using JSON.NET as the default JSON serializer in ASP.NET MVC 3 - is it possible?
If you also want to use JSON.Net for controller action parameters so during the model binding then you need write your own ValueProviderFactory
implementation.
And you need to register your implementation with:
ValueProviderFactories.Factories
.Remove(ValueProviderFactories.Factories
.OfType<JsonValueProviderFactory>().Single());
ValueProviderFactories.Factories.Add(new MyJsonValueProviderFactory());
You can use the built in JsonValueProviderFactory
as an example or this article: ASP.NET MVC 3 – Improved JsonValueProviderFactory using Json.Net
Using JSON.NET as the default JSON serializer in ASP.NET MVC 3 - is it possible?
I believe the best way to do it, is - as described in your links - to extend ActionResult or extend JsonResult directly.
As for the method JsonResult that is not virtual on the controller that's not true, just choose the right overload. This works well:
protected override JsonResult Json(object data, string contentType, Encoding contentEncoding)
EDIT 1: A JsonResult extension...
public class JsonNetResult : JsonResult
{
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
throw new ArgumentNullException("context");
var response = context.HttpContext.Response;
response.ContentType = !String.IsNullOrEmpty(ContentType)
? ContentType
: "application/json";
if (ContentEncoding != null)
response.ContentEncoding = ContentEncoding;
// If you need special handling, you can call another form of SerializeObject below
var serializedObject = JsonConvert.SerializeObject(Data, Formatting.Indented);
response.Write(serializedObject);
}
EDIT 2: I removed the check for Data being null as per the suggestions below. That should make newer versions of JQuery happy and seems like the sane thing to do, as the response can then be unconditionally deserialized. Be aware though, that this is not the default behavior for JSON responses from ASP.NET MVC, which rather responds with an empty string, when there's no data.
Change Default JSON Serializer Used In ASP MVC3
your best bet is to inherit from JsonResult class and override Execute method like
public class CustomJsonResult: JsonResult
{
public CustomJsonResult()
{
JsonRequestBehavior = JsonRequestBehavior.DenyGet;
}
public override void ExecuteResult(ControllerContext context) {
if (context == null) {
throw new ArgumentNullException("context");
}
if (JsonRequestBehavior == JsonRequestBehavior.DenyGet &&
String.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase)) {
throw new InvalidOperationException(MvcResources.JsonRequest_GetNotAllowed);
}
HttpResponseBase response = context.HttpContext.Response;
if (!String.IsNullOrEmpty(ContentType)) {
response.ContentType = ContentType;
}
else {
response.ContentType = "application/json";
}
if (ContentEncoding != null) {
response.ContentEncoding = ContentEncoding;
}
if (Data != null) {
CustomJsSerializer serializer = new CustomJsSerializer();
response.Write(serializer.Serialize(Data));
}
}
}
code is taken from JsonResult class of mvc3 and changed this line
JavaScriptSerializer serializer = new JavaScriptSerializer();
to
CustomJsSerializer serializer = new CustomJsSerializer();
you can use this class in action method like
public JsonResult result()
{
var model = GetModel();
return new CustomJsonResult{Data = model};
}
Additionally you can override json method of Controller class in your Base controller like
public class BaseController:Controller
{
protected internal override JsonResult Json(object data)
{
return new CustomJsonResult { Data = data };
}
}
now if you have all your controllers from BaseController then return Json(data)
will call your serialization scheme. There are also other overloads of Json
method that you may choose to override.
How to set json serializer settings in asp.net core 3?
AddMvc
returns an IMvcBuilder
implementation, which has a corresponding AddJsonOptions
extension method. The new-style methods AddControllers
, AddControllersWithViews
, and AddRazorPages
also return an IMvcBuilder
implementation. Chain with these in the same way you would chain with AddMvc
:
services.AddControllers()
.AddJsonOptions(options =>
{
// ...
});
Note that options
here is no longer for Json.NET, but for the newer System.Text.Json
APIs. If you still want to use Json.NET, see tymtam's answer
How do I set Json.NET as default serializer in asp.net core 3.1
refined my google search and it has been answered here:
https://stackoverflow.com/a/57652537/192727
I followed exactly what @Tao Zhou suggested and it did the trick.
C# WebAPI: Set default JSON serializer to NewtonSoft JSON
var formatter = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
formatter.SerializerSettings = new JsonSerializerSettings
{
Formatting = Formatting.Indented,
TypeNameHandling = TypeNameHandling.Objects,
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
Would be placed in your global.asax
Related Topics
Finding Holes in 2D Point Sets
Convert Linq Expression "Obj =≫ Obj.Prop" into "Parent =≫ Parent.Obj.Prop"
Why Does Adding a New Value to List≪≫ Overwrite Previous Values in the List≪≫
Suspending Event Not Raising Using Winrt
Desktop Applicaton Not Opening After Installation in Client System
How to Get an Htmlelement Value Inside Frames/Iframes
Saml Assertion in a Xml Using C#
How to Secure an ASP.NET Web API
Which .Net Dependency Injection Frameworks Are Worth Looking Into
How to Ensure That a Division of Integers Is Always Rounded Up
Jquery Ui Dialog With ASP.NET Button Postback
How to Read Appsettings Values from a .Json File in ASP.NET Core
How to Execute an .SQL Script File Using C#