2017-04-19 66 views
1

我們正試圖將舊的API遷移到我們當前的.Net Core Web API中。我們目前的API使用camelCasing返回JSON,但我們的舊API使用PascalCasing,我們不想更新客戶端。.Net Core Web API不同的JSON外殼每個控制器

有沒有什麼方法可以指定我們想要使用每個控制器的序列化策略,而不是整個服務的全局?

+0

[asp.net 1.0核心API的網站使用駝峯](可能的重複http://stackoverflow.com/questions/38139607/asp-net-core-1-0-web-api-use-camelcase) – Set

+0

我不這麼認爲,我相信只是要求在整個API上使用camelCase,而不是每個控制器 –

+0

我們最終添加了[JsonProperty ]標記到我們相關模型中的每個屬性。不是理想的解決方案(我們有很多模型),但它現在正在工作。 –

回答

1

是的,你可以通過在控制器上使用屬性來實現它。請參見下面的示例:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] 
public class CustomJsonFormatter : ActionFilterAttribute 
{ 
    private readonly string formatName = string.Empty; 
    public CustomJsonFormatter(string _formatName) 
    { 
     formatName = _formatName; 
    } 

    public override void OnActionExecuted(ActionExecutedContext context) 
    { 
     if (context == null || context.Result == null) 
     { 
      return; 
     } 

     var settings = JsonSerializerSettingsProvider.CreateSerializerSettings(); 

     if (formatName == "camel") 
     { 
      settings.ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver(); 
     }    
     else 
     { 
      settings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver(); 
     } 

     var formatter = new JsonOutputFormatter(settings, ArrayPool<Char>.Shared); 

     (context.Result as Microsoft.AspNetCore.Mvc.OkObjectResult).Formatters.Add(formatter); 
    } 
} 

,這裏是你的控制器:

[CustomJsonFormatter("camel")] 
[Route("api/[controller]")] 
public class ValuesController : Controller 
{ 
    // GET: api/values 
    [HttpGet] 
    public IActionResult Get() 
    { 
     Car car = new Car { Color = "red", Make = "Nissan" }; 

     return Ok(car); 
    }   
} 
相關問題