Can I customize my own serializer for an area in ASP.Net?

I am trying to configure a scope to use some of the custom JSON serializer settings for a newly created scope in an ASP.Net project. I am writing a web API controller.

Unfortunately, I cannot affect the whole project (a lot of legacy code), otherwise I would just do:

var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
json.SerializerSettings.Converters = new List<JsonConverter>() { new StringEnumConverter() };

But I can change this new area, but I consider it necessary.

Is it possible to set up this new area (there are other areas that I don’t want to touch, either) in the same way as above?

+4
source share
1 answer
  • , JsonResult. .
  • Json, JsonResult.
  • , , BaseController

:

public abstract class BaseController : Controller
{
    protected override JsonResult Json(object data, string contentType, Encoding contentEncoding, JsonRequestBehavior behavior)
    {
        return new MySpecialJsonResult //Inherits from JsonResult and contains the desired serializer implementation
        {
            Data = data,
            ContentType = contentType,
            ContentEncoding = contentEncoding,
            JsonRequestBehavior = behavior
        };
    }
}

public class EmployeeController : BaseController
{
    public JsonResult Index()
    {
        //Your custom serializer will be used...
        return Json(new{Text="Hello"},JsonRequestBehavior.AllowGet);
    }
}
+3

All Articles