ASP.NET MVC 6上每个控制器的特定JSON设置



我需要在ASP.NET MVC 6 webApi中为每个控制器设置特定的JSON。我发现了这个适用于MVC 5的示例(我希望!):按控制器在ASP.NET WebAPI上强制CamelCase

using System;
using System.Linq;
using System.Web.Http.Controllers;
using System.Net.Http.Formatting;
using Newtonsoft.Json.Serialization;
public class CamelCaseControllerConfigAttribute : Attribute, IControllerConfiguration 
{
    public void Initialize(HttpControllerSettings controllerSettings, HttpControllerDescriptor controllerDescriptor)
    {
        var formatter = controllerSettings.Formatters.OfType<JsonMediaTypeFormatter>().Single();
        controllerSettings.Formatters.Remove(formatter);
        formatter = new JsonMediaTypeFormatter
        {
            SerializerSettings = {ContractResolver = new CamelCasePropertyNamesContractResolver()}
        };
        controllerSettings.Formatters.Add(formatter);
    }
}

此类工作良好:

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);
        }
    }
}

用途:

[Route("api/mobile/businessrequest")]
[Authorize]
[MobileControllerConfigurator]
public class MobileBusinessRequestController : BaseController
{

您可以在控制器操作方法上使用JsonResult的返回类型。在我的案例中,我需要特定的操作来返回某些遗留场景的Pascal case。JsonResult对象允许您传递一个可选参数作为JsonSerializerSettings。

public JsonResult Get(string id)
{
    var data = _service.getData(id);
    return Json(data, new JsonSerializerSettings
    {
        ContractResolver = new DefaultContractResolver()
    });
}

为了获得更一致的控制器方法签名,我最终创建了一个扩展方法:

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

现在我可以简单地调用控制器中的扩展方法,如下所示:

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

相关内容

  • 没有找到相关文章

最新更新