我想用 JSON.NET 替换默认的 WCF JSON(适用于所有数据类型)序列化。我已经搜索了整个网络,但找不到有效的解决方案。
这是我的对象:
[JsonObject]
public class TestObject
{
[JsonProperty("JsonNetName")]
public string Name = "John";
[JsonProperty]
public DateTime Date = DateTime.Now;
}
这是我的 WCF 函数:
[OperationContract]
[WebGet(BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json)]
List<TestObject> Get();
这是 Global.asax 中的代码:
protected void Application_Start(object sender, EventArgs e)
{
// Create Json.Net formatter serializing DateTime using the ISO 8601 format
var serializerSettings = new JsonSerializerSettings();
serializerSettings.Converters.Add(new IsoDateTimeConverter());
serializerSettings.Converters.Add(new BinaryConverter());
serializerSettings.Converters.Add(new JavaScriptDateTimeConverter());
serializerSettings.Converters.Add(new BinaryConverter());
serializerSettings.Converters.Add(new StringEnumConverter());
var config = HttpHostConfiguration.Create().Configuration;
Microsoft.ApplicationServer.Http.JsonMediaTypeFormatter jsonFormatter = config.OperationHandlerFactory.Formatters.JsonFormatter;
config.OperationHandlerFactory.Formatters.Remove(jsonFormatter);
config.OperationHandlerFactory.Formatters.Insert(0, new JsonNetMediaTypeFormatter(serializerSettings));
var httpServiceFactory = new HttpServiceHostFactory
{
OperationHandlerFactory = config.OperationHandlerFactory,
MessageHandlerFactory = config.MessageHandlerFactory
};
//Routing
RouteTable.Routes.Add(
new ServiceRoute(
"Brands", httpServiceFactory,
typeof(Brands)));
}
这是 Web.Config:
<endpointBehaviors>
<behavior name="Behavior_Brands">
<webHttp defaultOutgoingResponseFormat="Json" defaultBodyStyle="Bare" />
</behavior>
</endpointBehaviors>
和服务部分:
<service name="TestApp.CoreWCF.Brands">
<endpoint address="" behaviorConfiguration="Behavior_Brands" binding="webHttpBinding" contract="TestApp.CoreWCF.IBrands">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
</service>
最后,这是我在启动 URL 时得到的:
“ http://localhost:30000/Brands/Get ”
[{"Date":"\/Date(1354364412708+0200)\/","Name":"John"}, {"Date":"\/Date(1354364412708+0200)\/","Name":"John"}]
JSON 答案显然忽略了 JSON.NET 属性。