CaseClass 中使用的变量在发送请求时会转换为snake大小写,但需要从snake大小写转换而需要与 CaseClass 默认情况下,在收到请求时。
请求发件人代码
public static void Main(string[] args)
{
var caseClass = new CaseClass
{
FirstName = "xxx",
LastName = "y"
};
using (var proxy = new CustomWebClient())
{
var ser = new DataContractJsonSerializer(typeof(CaseClass));
var mem = new MemoryStream();
ser.WriteObject(mem, CaseClass);
proxy.Headers["Content-type"] = "application/x-www-form-urlencoded";
proxy.Headers["Authorization"] = token.token_type + " " + token.access_token;
proxy.Encoding = Encoding.UTF8;
var data = Encoding.UTF8.GetString(mem.ToArray(), 0, (int)mem.Length);
try
{
var rdata = proxy.UploadString(new Uri("http://localhost:56612/api/v1.0/users/"), "POST", data);
var result = JsonConvert.DeserializeObject<ItemResponse>(rdata);
}
catch (WebException ex)
{
if (ex.Response is HttpWebResponse)
{
var resp = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
dynamic obj = JsonConvert.DeserializeObject(resp);
Console.WriteLine(obj);
Console.ReadKey();
}
}
}
}
[Serializable]
[DataContract]
public class CaseClass
{
[DataMember(Name = "first_name")]
public string FirstName { get; set; }
[DataMember(Name = "last_name")]
public string LastName { get; set; }
}
接收请求的发布方法
[HttpPost]
[Route("api/v1.0/users")]
public void TestMethod(CaseClass caseClass)
{
//processing the request
}
因此,在发送请求时,需要将 CaseClass 成员转换为蛇形外壳,并且在接收请求时,需要从蛇形外壳转换 CaseClass 成员。
注意:我不只使用CaseClass,通常需要为所有类进行转换。