C#POST JSON作为所有请求的驼峰式案例 [英] c# POST JSON as camel case for all requests

查看:139
本文介绍了C#POST JSON作为所有请求的驼峰式案例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经将.Net对象作为驼峰式JSON返回,并且我这样做是这样的:

I already return .Net objects as camel cased JSON and I have done this like so:

// Web API configuration and services
var formatters = config.Formatters;
var jsonFormatter = formatters.JsonFormatter;
var serializerSettings = jsonFormatter.SerializerSettings;

// Remove XML formatting
formatters.Remove(config.Formatters.XmlFormatter);
jsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));

// Configure our JSON output
serializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
serializerSettings.Formatting = Formatting.Indented;

这一切都很好,但是今天我发布到一个外部API并出现错误,事实证明,问题在于使用Pascal大小写而不是Camel大小写的json格式.我发布的数据看起来像这样:

This all works fine, but today I was posting to an external API and getting an error, it turns out that the issue is with the json formatting using Pascal case instead of Camel case. My POSTed data looked like this:

{"CartId":"8fb3792f-81af-45e6-92f6-f08366624f1e","Id":"944990015513953203","Quantity":5}

我四处搜寻,找到了一种解决方案,可以将数据转换为驼峰式的情况,如下所示:

I searched around and found a solution for turning that data into camel case, like this:

var serializer = new JsonSerializer()
{
    ContractResolver = new CamelCasePropertyNamesContractResolver()
};

var json = JObject.FromObject(model, serializer);

但是您可以猜到,这真的不适合,因为我不想在每个控制器的每个POST操作中都必须这样做.我以为上面的WebApiConfig可以应用于所有响应以及请求.

but as you can guess, this is not really suitable as I don't want to have to do that in every POST action in every controller. I would have assumed that the WebApiConfig above would have applied to all responses as well as requests.

有人知道我如何打开全球骆驼保护套吗?

Does anyone know how I can turn on a global camel case switch?

推荐答案

在这种情况下,您不想为所有请求更改它,因此只需在要发送给他们的模型上使用属性即可.

In this case you don't want to change it for all requests so just use attributes on your model you are sending to them.

using Newtonsoft.Json;

[JsonProperty("Name")]
public string Name { get; set; }

这将确保您以所需的格式将其发送给他们.

That will ensure you send it to them in the format you want.

这篇关于C#POST JSON作为所有请求的驼峰式案例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆