如何在WCF REST端点中将JSON响应转为CamelCase格式?
没问题,在现有WCF REST服务里完全能实现PascalCase转CamelCase的JSON输出,不用额外新建Web API或MVC项目,给你两种实用方案:
解决方案:WCF REST返回CamelCase格式JSON
先明确下需求:你的WCF响应类用的是PascalCase命名(比如Packages、Messages),但希望返回的JSON字段是camelCase(比如packages、messages),下面两种方案都能满足:
方案一:手动指定字段名(简单直接,适合小体量模型)
WCF默认的DataContractJsonSerializer支持通过DataMember特性的Name参数,直接指定JSON输出的字段名。你只需要给响应类及其子类的每个属性加上这个配置:
using System.Runtime.Serialization; [DataContract] public class PackageConfigResponse { [DataMember(Name = "packages")] public List<Package> Packages { get; set; } [DataMember(Name = "messages")] public MessageInfo Messages { get; set; } } // 子类型也要做同样处理 [DataContract] public class Package { [DataMember(Name = "packageId")] public int PackageId { get; set; } // 其他属性按此格式添加DataMember } [DataContract] public class MessageInfo { [DataMember(Name = "messageType")] public string MessageType { get; set; } // 其他属性按此格式添加DataMember }
这种方法优点是上手快,不需要额外配置类;缺点是如果模型类多、属性多,需要逐个修改,比较繁琐。
方案二:自定义序列化行为(自动转换,适合大量模型)
如果你的模型类数量多,不想手动改每个属性,可以自定义WCF的序列化行为,自动把PascalCase转为CamelCase。这里推荐用你熟悉的Newtonsoft.Json(Json.NET)来替换默认序列化器,配置起来更灵活:
步骤1:实现Newtonsoft.Json调度格式化器
创建一个格式化器,用Json.NET的CamelCasePropertyNamesContractResolver自动处理命名转换:
using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using System.ServiceModel.Channels; using System.ServiceModel.Dispatcher; using System.IO; using System.Text; public class NewtonsoftJsonDispatchFormatter : IDispatchMessageFormatter { private readonly OperationDescription _operation; private readonly JsonSerializerSettings _jsonSettings; public NewtonsoftJsonDispatchFormatter(OperationDescription operation) { _operation = operation; // 配置驼峰命名解析器 _jsonSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver(), Formatting = Formatting.Indented // 可选,格式化JSON输出更易读 }; } // 处理请求反序列化(如果需要支持camelCase格式的请求,可保留此逻辑) public void DeserializeRequest(Message message, object[] parameters) { var bodyReader = message.GetReaderAtBodyContents(); bodyReader.ReadStartElement("Binary"); var jsonBytes = bodyReader.ReadContentAsBase64(); var json = Encoding.UTF8.GetString(jsonBytes); var paramType = _operation.Messages[0].Body.Parts[0].Type; parameters[0] = JsonConvert.DeserializeObject(json, paramType, _jsonSettings); } // 处理响应序列化,核心是用Json.NET生成camelCase的JSON public Message SerializeReply(MessageVersion messageVersion, object[] parameters, object result) { var json = JsonConvert.SerializeObject(result, _jsonSettings); var bytes = Encoding.UTF8.GetBytes(json); var stream = new MemoryStream(bytes); var replyMessage = Message.CreateMessage(messageVersion, null, new RawBodyWriter(stream)); replyMessage.Properties.Add(WebBodyFormatMessageProperty.Name, new WebBodyFormatMessageProperty(WebContentFormat.Json)); var httpResponse = replyMessage.Properties[HttpResponseMessageProperty.Name] as HttpResponseMessageProperty ?? new HttpResponseMessageProperty(); httpResponse.Headers[HttpResponseHeader.ContentType] = "application/json; charset=utf-8"; replyMessage.Properties[HttpResponseMessageProperty.Name] = httpResponse; return replyMessage; } // 辅助类:处理原始流写入 private class RawBodyWriter : BodyWriter { private readonly Stream _stream; public RawBodyWriter(Stream stream) : base(true) => _stream = stream; protected override void OnWriteBodyContents(XmlDictionaryWriter writer) { writer.WriteStartElement("Binary"); var buffer = new byte[1024]; int bytesRead; while ((bytesRead = _stream.Read(buffer, 0, buffer.Length)) > 0) { writer.WriteBase64(buffer, 0, bytesRead); } writer.WriteEndElement(); } } }
步骤2:创建自定义WCF行为
让WCF使用我们刚才的格式化器:
using System.ServiceModel.Description; using System.ServiceModel.Dispatcher; public class NewtonsoftJsonBehavior : WebHttpBehavior { protected override IDispatchMessageFormatter GetRequestDispatchFormatter(OperationDescription operationDescription, ServiceEndpoint endpoint) { return new NewtonsoftJsonDispatchFormatter(operationDescription); } protected override IDispatchMessageFormatter GetReplyDispatchFormatter(OperationDescription operationDescription, ServiceEndpoint endpoint) { return new NewtonsoftJsonDispatchFormatter(operationDescription); } }
步骤3:注册行为(二选一)
方式A:代码注册行为
在服务启动时添加这个行为:
var serviceHost = new ServiceHost(typeof(FormsConfigTool)); var endpoint = serviceHost.AddServiceEndpoint(typeof(IFormsConfigTool), new WebHttpBinding(), ""); endpoint.Behaviors.Add(new NewtonsoftJsonBehavior()); serviceHost.Open();
方式B:配置文件注册行为
先注册行为扩展,再给端点绑定:
<system.serviceModel> <extensions> <behaviorExtensions> <!-- 替换成你的命名空间和程序集名称 --> <add name="newtonsoftJsonBehavior" type="YourNamespace.NewtonsoftJsonBehaviorElement, YourAssemblyName"/> </behaviorExtensions> </extensions> <behaviors> <endpointBehaviors> <behavior name="CamelCaseJsonBehavior"> <newtonsoftJsonBehavior /> <webHttp /> </behavior> </endpointBehaviors> </behaviors> <services> <service name="YourNamespace.FormsConfigTool"> <endpoint address="" behaviorConfiguration="CamelCaseJsonBehavior" binding="webHttpBinding" contract="YourNamespace.IFormsConfigTool"/> </service> </services> </system.serviceModel>
对应的行为元素类:
using System.ServiceModel.Configuration; public class NewtonsoftJsonBehaviorElement : BehaviorExtensionElement { public override Type BehaviorType => typeof(NewtonsoftJsonBehavior); protected override object CreateBehavior() { return new NewtonsoftJsonBehavior(); } }
总结
- 模型少、属性少:优先选方案一,简单快捷;
- 模型多、想自动转换:选方案二,一次配置全量生效,还能利用Json.NET的其他序列化特性。
内容的提问来源于stack exchange,提问作者Code-Strings
相关产品推荐
相关产品推荐

