Web Api 中返回JSON 转成驼峰给前端的机制

本文介绍了如何在Web API中通过自定义内容协商(Content Negotiation)策略,确保仅返回JSON格式的数据,并使用驼峰式命名。通过实现IContentNegotiator并注册自定义的JsonMediaTypeFormatter,避免每次请求时重复创建formatter,降低了性能开销。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在使用Web Api的时候,有时候只想返回JSON

最好的方法是使用自定义的只返回Json Result的content negotiation代替Web Api中默认的content negotiation。

Conneg通过实现IContentNegotiator的Negotiator方法实现扩展。Negotiator方法返回ContentNegotiationResult(它包装了你选择的headers和formatter)。

下面的方法通过传递一个JsonMediaTypeFormatter给自定义的conneg negotiator,让它一直返回applicaton/json 的content-type以及JsonMediaTypeFormatter。这种方法避免了每次请求都要重新创建一次formatter。

代码如下:in webApi config new class

复制代码

public class JsonContentNegotiator : IContentNegotiator
{
    private readonly JsonMediaTypeFormatter _jsonFormatter;

    public JsonContentNegotiator(JsonMediaTypeFormatter formatter) 
    {
        _jsonFormatter = formatter;    
    }

    public ContentNegotiationResult Negotiate(Type type, HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters)
    {
        var result = new ContentNegotiationResult(_jsonFormatter, new MediaTypeHeaderValue("application/json"));
        return result;
    }
}

复制代码

接下来,你需要在HttpConfiguration实例上注册你的新的实现机制:

   public class WebApiConfig
    {
        public static void Register(HttpConfiguration config, IAppBuilder appBuilder)
        {
           //

            //Return json with lower case first letter of property names
            var jsonFormatter = new JsonMediaTypeFormatter();
            config.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter));

            appBuilder.UseWebApi(config);
        }
    }
通过替换默认的DefaultContentNegotiator,我们使用我们自定义的JsonContentNegotiator,它只支持Json,而且可以马上返回。

如果你想更深入的了解Content Negotiation的知识,你可以查看作者的这篇文章

总结

通过使用自定义的JsonContentNegotiator替换系统默认的DefaultContentNegotiator,很好的实现Web Api只返回Json的功能,而且没有额外的开销。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值