wcf datetime json format
wcf 内置的json序列化工具,有时需要替换,或者特殊情况的处理,需要修改。
我也遇到了Dto属性类型是datetime,json的反序列化 和 序列号不友好。
这是国外网站的一个方案:Replacing WCF DataContractJsonSerializer with Newtonsoft JsonSerializer
不过时间格式还不是我想要的,他是发布在GitHub上,于是简单修改了时间格式,使更符合国情。
需要引用新写的库 WcfNewtonsoftJsonSerializer ,然后配置文件配置好。
关键配置部分:behaviorExtensions、endpointBehaviors、webHttpBinding
<system.serviceModel>
<extensions>
<behaviorExtensions>
<add name="newtonsoftJsonBehavior" type="WcfNewtonsoftJsonSerializer.NewtonsoftJsonBehaviorExtension, WcfNewtonsoftJsonSerializer" />
</behaviorExtensions>
</extensions>
<behaviors>
<endpointBehaviors>
<behavior name="restEndPointBehavior">
<webHttp helpEnabled="true" />
<newtonsoftJsonBehavior />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="restServiceBehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="true" httpHelpPageEnabled="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<webHttpBinding>
<binding name="restWebHttpBinding"
contentTypeMapper="WcfNewtonsoftJsonSerializer.NewtonsoftJsonContentTypeMapper, WcfNewtonsoftJsonSerializer"
allowCookies="false"
bypassProxyOnLocal="false"
hostNameComparisonMode="StrongWildcard"
maxBufferPoolSize="524288"
maxBufferSize="2147483647"
closeTimeout="00:01:00"
openTimeout="00:01:00"
receiveTimeout="00:02:00"
sendTimeout="00:02:00"
maxReceivedMessageSize="2147483647"
transferMode="Buffered">
<security mode="None">
<transport clientCredentialType="None" />
</security>
<readerQuotas maxArrayLength="2147483647"
maxBytesPerRead="2147483647"
maxDepth="2147483647"
maxNameTableCharCount="2147483647"
maxStringContentLength="2147483647" />
</binding>
</webHttpBinding>
</bindings>
<services>
<service name="WcfService1.Service1" behaviorConfiguration="restServiceBehavior">
<endpoint address=""
contract="WcfService1.IService1"
binding="webHttpBinding"
bindingConfiguration="restWebHttpBinding"
behaviorConfiguration="restEndPointBehavior" />
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
</system.serviceModel>
以下是WcfNewtonsoftJsonSerializer项目的关键代码:
public class NewtonsoftJsonBehavior : WebHttpBehavior
{
public override void Validate( ServiceEndpoint endpoint )
{
base.Validate( endpoint ); var elements = endpoint.Binding.CreateBindingElements();
var webEncoder = elements.Find<WebMessageEncodingBindingElement>();
if ( webEncoder == null )
{
throw new InvalidOperationException( "This behavior must be used in an endpoint with the WebHttpBinding (or a custom binding with the WebMessageEncodingBindingElement)." );
} foreach ( var operation in endpoint.Contract.Operations )
{
ValidateOperation( operation );
}
} protected override IDispatchMessageFormatter GetRequestDispatchFormatter( OperationDescription operationDescription, ServiceEndpoint endpoint )
{
if ( IsGetOperation( operationDescription ) )
{
// no change for GET operations
return base.GetRequestDispatchFormatter( operationDescription, endpoint );
} if ( operationDescription.Messages[].Body.Parts.Count == )
{
// nothing in the body, still use the default
return base.GetRequestDispatchFormatter( operationDescription, endpoint );
} return new NewtonsoftJsonDispatchFormatter( operationDescription, true );
} protected override IDispatchMessageFormatter GetReplyDispatchFormatter( OperationDescription operationDescription, ServiceEndpoint endpoint )
{
if ( operationDescription.Messages.Count == || operationDescription.Messages[].Body.ReturnValue.Type == typeof( void ) )
{
return base.GetReplyDispatchFormatter( operationDescription, endpoint );
}
else
{
return new NewtonsoftJsonDispatchFormatter( operationDescription, false );
}
} private void ValidateOperation( OperationDescription operation )
{
if ( operation.Messages.Count > )
{
if ( operation.Messages[].Body.Parts.Count > )
{
throw new InvalidOperationException( "Operations cannot have out/ref parameters." );
}
} var bodyStyle = GetBodyStyle( operation );
var inputParameterCount = operation.Messages[].Body.Parts.Count;
if ( !IsGetOperation( operation ) )
{
var wrappedRequest = bodyStyle == WebMessageBodyStyle.Wrapped || bodyStyle == WebMessageBodyStyle.WrappedRequest;
if ( inputParameterCount == && wrappedRequest )
{
throw new InvalidOperationException( "Wrapped body style for single parameters not implemented in this behavior." );
}
} var wrappedResponse = bodyStyle == WebMessageBodyStyle.Wrapped || bodyStyle == WebMessageBodyStyle.WrappedResponse;
var isVoidReturn = operation.Messages.Count == || operation.Messages[].Body.ReturnValue.Type == typeof( void );
if ( !isVoidReturn && wrappedResponse )
{
throw new InvalidOperationException( "Wrapped response not implemented in this behavior." );
}
} private WebMessageBodyStyle GetBodyStyle( OperationDescription operation )
{
var wga = operation.Behaviors.Find<WebGetAttribute>();
if ( wga != null )
{
return wga.BodyStyle;
} var wia = operation.Behaviors.Find<WebInvokeAttribute>();
if ( wia != null )
{
return wia.BodyStyle;
} return DefaultBodyStyle;
} private bool IsGetOperation( OperationDescription operation )
{
var wga = operation.Behaviors.Find<WebGetAttribute>();
if ( wga != null )
{
return true;
} var wia = operation.Behaviors.Find<WebInvokeAttribute>();
if ( wia != null )
{
return wia.Method == "HEAD";
} return false;
}
}
public class NewtonsoftJsonBehaviorExtension : BehaviorExtensionElement
{
public override Type BehaviorType
{
get { return typeof ( NewtonsoftJsonBehavior ); }
} protected override object CreateBehavior()
{
return new NewtonsoftJsonBehavior();
}
}
public class NewtonsoftJsonContentTypeMapper : WebContentTypeMapper
{
public override WebContentFormat GetMessageFormatForContentType( string contentType )
{
return WebContentFormat.Raw;
}
}
public class NewtonsoftJsonDispatchFormatter : IDispatchMessageFormatter
{
private readonly OperationDescription _operation;
private readonly Dictionary<string, int> _parameterNames; public NewtonsoftJsonDispatchFormatter( OperationDescription operation, bool isRequest )
{
_operation = operation;
if ( isRequest )
{
var operationParameterCount = operation.Messages[].Body.Parts.Count;
if ( operationParameterCount > )
{
_parameterNames = new Dictionary<string, int>();
for ( var i = ; i < operationParameterCount; i++ )
{
_parameterNames.Add( operation.Messages[].Body.Parts[i].Name, i );
}
}
}
} public void DeserializeRequest( Message message, object[] parameters )
{
object bodyFormatProperty;
if ( !message.Properties.TryGetValue( WebBodyFormatMessageProperty.Name, out bodyFormatProperty ) ||
( bodyFormatProperty as WebBodyFormatMessageProperty ).Format != WebContentFormat.Raw )
{
throw new InvalidOperationException( "Incoming messages must have a body format of Raw. Is a ContentTypeMapper set on the WebHttpBinding?" );
} var bodyReader = message.GetReaderAtBodyContents();
bodyReader.ReadStartElement( "Binary" );
var rawBody = bodyReader.ReadContentAsBase64();
var ms = new MemoryStream( rawBody ); var sr = new StreamReader( ms );
var serializer = new Newtonsoft.Json.JsonSerializer();
if ( parameters.Length == )
{
// single parameter, assuming bare
parameters[] = serializer.Deserialize( sr, _operation.Messages[].Body.Parts[].Type );
}
else
{
// multiple parameter, needs to be wrapped
Newtonsoft.Json.JsonReader reader = new Newtonsoft.Json.JsonTextReader( sr );
reader.Read();
if ( reader.TokenType != Newtonsoft.Json.JsonToken.StartObject )
{
throw new InvalidOperationException( "Input needs to be wrapped in an object" );
} reader.Read();
while ( reader.TokenType == Newtonsoft.Json.JsonToken.PropertyName )
{
var parameterName = reader.Value as string;
reader.Read();
if ( _parameterNames.ContainsKey( parameterName ) )
{
var parameterIndex = _parameterNames[parameterName];
parameters[parameterIndex] = serializer.Deserialize( reader, _operation.Messages[].Body.Parts[parameterIndex].Type );
}
else
{
reader.Skip();
} reader.Read();
} reader.Close();
} sr.Close();
ms.Close();
} public Message SerializeReply( MessageVersion messageVersion, object[] parameters, object result )
{
byte[] body;
var serializer = new Newtonsoft.Json.JsonSerializer();
serializer.Converters.Add( new IsoDateTimeConverter() {DateTimeFormat = "yyyy-MM-dd HH:mm:ss", DateTimeStyles = DateTimeStyles.None} ); using ( var ms = new MemoryStream() )
{
using ( var sw = new StreamWriter( ms, Encoding.UTF8 ) )
{
using ( Newtonsoft.Json.JsonWriter writer = new Newtonsoft.Json.JsonTextWriter( sw ) )
{
//writer.Formatting = Newtonsoft.Json.Formatting.Indented;
serializer.Serialize( writer, result );
sw.Flush();
body = ms.ToArray();
}
}
} var replyMessage = Message.CreateMessage( messageVersion, _operation.Messages[].Action, new RawBodyWriter( body ) );
replyMessage.Properties.Add( WebBodyFormatMessageProperty.Name, new WebBodyFormatMessageProperty( WebContentFormat.Raw ) );
var respProp = new HttpResponseMessageProperty();
respProp.Headers[HttpResponseHeader.ContentType] = "application/json";
replyMessage.Properties.Add( HttpResponseMessageProperty.Name, respProp );
return replyMessage;
}
}
public class RawBodyWriter : BodyWriter
{
private readonly byte[] _content; public RawBodyWriter( byte[] content )
: base( true )
{
_content = content;
} protected override void OnWriteBodyContents( XmlDictionaryWriter writer )
{
writer.WriteStartElement( "Binary" );
writer.WriteBase64( _content, , _content.Length );
writer.WriteEndElement();
}
}
wcf datetime json format的更多相关文章
- 最新版ABP 动态WebAPI 日期转json带T的解决方案| ABP DateTIme Json format
ABP动态webapi返回的json数据中,日期时间带T还有毫秒数的问题,在以往的版本中可以使用下面方法解决: 在XXXAbpWebApiModule中加上下面的代码: 很老的很老的版本有效: pub ...
- SpringMVC 设置全局DateTime json返回格式
对于部分返回DateTime的项目,只需要在指定属性上添加@JsonSerialize 使用自定义的json转换格式即可自定义返回DateTime格式 但是对于项目中返回有多个DateTime字段来说 ...
- WCF Ajax Json的应用
WCF Ajax 的应用网上实际上有很多, 如: Ajax与Wcf交互-JSON jQuery调用WCF服务传递JSON对象 WCF以Json格式返回对象,客户端以JS调用显示 关于SoapUI的介绍 ...
- 解决asp.net core 日期格式 datetime Json返回 带T的问题
原文:解决asp.net core 日期格式 datetime Json返回 带T的问题 记录一下: Startup中,将 services.AddMvc(); 改为: services.AddMvc ...
- WCF JSON DATETIME JSON.NET (Newtonsoft.Json.dll)
[DataMember] public DateTime? myTime { get; set; } var timeFormat = new JsonSerializerSettings() { D ...
- WCF 生产json对外的接口
调用wcf public ActionResult Index() { ViewBag.Message = "修改此模板以快速启动你的 ASP.NET MVC 应用程序."; WC ...
- python模块time&datetime&json & picle&14.logging等
本节大纲: 模块介绍 time &datetime模块 random os sys shutil json & picle shelve xml处理 yaml处理 configpars ...
- Entity Framework + WCF REST JSON Service
利用EF 和WCF 建立一个REST JSON Service. 首先我们要下载一个Visual Studio 的Template 叫 "ADO.NET C# POCO Entity Gen ...
- WCF返回JSON的详细配置
开发环境:VS2008,c# 1.新建个WCF服务网站 文件-新建-网站-WCF服务 2,运行一下,提示配置WEB.CONFIG,点击确认. 3,打开web.config增加如下节点: <ser ...
随机推荐
- django model项目外操作
方法1: python manage.py shell 然后import对应的model并操作 方法2: 新建py脚本 import sys import os pwd = os.path.dirna ...
- “全栈2019”Java第八十章:外部类是否能实现本类中的接口?
难度 初级 学习时间 10分钟 适合人群 零基础 开发语言 Java 开发环境 JDK v11 IntelliJ IDEA v2018.3 文章原文链接 "全栈2019"Java第 ...
- [BZOJ4530][Bjoi2014]大融合(LCT)
传送门 大佬们似乎都是用树剖+并查集优雅地A了此题 然后我太弱了,只能打打LCT的板子 虽然的确可以挺无脑的A掉…… 不过至少这题教了我该怎么维护LCT上虚子树的信息,具体看这里 首先,答案很明显是断 ...
- 二,PHP缓存机制详解
一,PHP缓存机制详解 我们可以使用PHP自带的缓存机制来完成页面静态化,但是仅靠PHP自身的缓存机制并不能完美的解决页面静态化,往往需要和其他静态化技术(通常是伪静态技术)结合使用. output ...
- web渗透-sql注入
何为sql注入 所谓SQL注入,就是通过把SQL命令插入到Web表单提交或输入域名或页面请求的查询字符串,最终达到欺骗服务器执行恶意的SQL命令,得到想要得到的信息. OWASPTop 10 此处的注 ...
- CentOS 中卸载 RPM 包文件
CentOS 中卸载 RPM 包文件 一.原由 因为之前卸载 openvas 这个工具,使用了 find / -name "openvas"-exec rm -rf {} \ ; ...
- ArchLinux下shadow服务报错
用着Linux蓦然开机就报错了.我是个对报错很敏感的,而是是开机报错. 这个的严重性,听一位前辈说过:如果开机报错你都不理它,慢慢的它就会宕机. 报错内容: shadow服务是Linux下用于校队pa ...
- [转]iOS系列译文:深入理解 CocoaPods
Cocoapods是 OS X 和 iOS 下的一个第三方库管理工具.你能使用CocoaPods添加被称作“Pods”的依赖库,并轻松管理它们的版本,而不用考虑当前的时间和开发环境. Cocoapod ...
- jquer 使用原生DOM对象
js中使document.getElementById("ID"); Jquery中可以使用$("#id") 或者$("#id").get( ...
- SimpleITK学习(二)图像读取
通常我会用simpleitk来读取dicom文件,主要是为了将dicom文件转换为numpy矩阵,便于输入神经网络,读取dicom文件可分为两种情况,一.单独的dicom文件 二.一系列dicom文件 ...