Specific JSON settings per controller on ASP.NET MVC 6

末鹿安然 提交于 2019-12-03 06:38:19
Mike Lunn

You can use a return type of JsonResult on your controller action methods. In my case, I needed specific actions to return Pascal Case for certain legacy scenarios. The JsonResult object allows you to pass an optional parameter as the JsonSerializerSettings.

public JsonResult Get(string id)
{
    var data = _service.getData(id);

    return Json(data, new JsonSerializerSettings
    {
        ContractResolver = new DefaultContractResolver()
    });

}

To have more consistent controller method signatures I ended up creating an extension method:

public static JsonResult ToPascalCase(this Controller controller, object model)
{
    return controller.Json(model, new JsonSerializerSettings
    {
        ContractResolver = new DefaultContractResolver()
    });
}

Now I can simply call the extension method inside my controller like below:

public IActionResult Get(string id)
{
    var data = _service.getData(id);
    return this.ToPascalCase(data);
}

This class works fine :

using System;
using System.Linq;
using Newtonsoft.Json.Serialization;
using Microsoft.AspNet.Mvc.Filters;
using Newtonsoft.Json;
using Microsoft.AspNet.Mvc.Formatters;

namespace Teedl.Web.Infrastructure
{
    [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)]

    public class MobileControllerConfiguratorAttribute : Attribute, IResourceFilter
    {
        private readonly JsonSerializerSettings serializerSettings;

        public MobileControllerConfiguratorAttribute()
        {
            serializerSettings = new JsonSerializerSettings()
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver(),
                TypeNameHandling = Newtonsoft.Json.TypeNameHandling.Objects,
                TypeNameAssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple,
                Binder = new TypeNameSerializationBinder("Teedl.Model.Mobile.{0}, Teedl.Model.ClientMobile")
        };
        }


        public void OnResourceExecuted(ResourceExecutedContext context)
        {
        }

        public void OnResourceExecuting(ResourceExecutingContext context)
        {
            var mobileInputFormatter = new JsonInputFormatter(serializerSettings);
            var inputFormatter = context.InputFormatters.FirstOrDefault(frmtr => frmtr is JsonInputFormatter);
            if (inputFormatter != null)
            {
                context.InputFormatters.Remove(inputFormatter);
            }
            context.InputFormatters.Add(mobileInputFormatter);

            var mobileOutputFormatter = new JsonOutputFormatter(serializerSettings);
            var outputFormatter = context.OutputFormatters.FirstOrDefault(frmtr => frmtr is JsonOutputFormatter);
            if (outputFormatter != null)
            {
                context.OutputFormatters.Remove(outputFormatter);
            }
            context.OutputFormatters.Add(mobileOutputFormatter);
        }
    }
}

Use :

[Route("api/mobile/businessrequest")]
[Authorize]
[MobileControllerConfigurator]
public class MobileBusinessRequestController : BaseController
{
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!