Web Services and C# Enums -摘自网络
Web Service Transparency
.NET support for web services is excellent in creating illusion of transparency. General process is quite straightforward:
- On the server we create a web service, decorating publicly visible methods with [WebMethod] attribute.
- On the client we add a web reference to the service, and proxy code is automatically generated for us by VIsual Studio. We can then call web service methods almost as if they were local methods.
All arguments and return values get magically XML-serialized, transmitted to the peer, and de-serialized to something very close to the original form. Ideally, this whole process should be automatic and seamless.
Imperfect Transparency of Enums
It turns out that enums are not as transparent as we'd like them to be. There are three sticky issues:
- If server-side code declares an enum and assigns specific numeric values to its members, these values will not be visible to the client.
- If server-side code declares a [Flags] enum with "compound" mask values (as in White = Red|Green|Blue), it is not properly reflected on the client side.
- If server or client transmits an "illegal" value which is outside of the scope of the enum, it causes an exception in XML de-serializer on the other side.
Numeric Values Are Not Preserved
If we have server-side definition like this:
enum StatusCode
{
Success = 200,
NotFound = 404,
Denied = 401
}
it is translated to client-side definition like this:
enum StatusCode
{
Success = 1,
NotFound = 2
Denied = 3
}
Corresponding WSDL looks as follows:
<s:simpleType name="StatusCode">
<s:restriction base="s:string">
<s:enumeration value="Success"/>
<s:enumeration value="NotFound"/>
<s:enumeration value="Denied"/>
</s:restriction>
</s:simpleType>
As one can see, there is no mension of numeric values in the WSDL. Proxy code generator on the client side does not have access to anything but WSDL. Therefore, it does not have a chance to get numeric values of enum members.
An important side effect of this phenomenon is that the relative order of enum members may not be preserved. For instance, in the example above, expression (StatusCode.NotFound > StatusCode.Denied)
is true on the server, and false on the client.
Relationships Between [Flags] Masks May Be Broken
Server-side declaration:
[Flags]
enum UserRights
{
Read = 16,
Write = 256,
Delete = 1024,
AllAccess = Read | Write | Delete
}
Client-side declaration (some insignificant decorations removed):
[Flags]
enum UserRights
{
Read = 1,
Write = 2,
Delete = 4,
AllAccess = 8
}
Corresponding WSDL:
<s:simpleType name="UserRights">
<s:restriction base="s:string">
<s:enumeration value="Read"/>
<s:enumeration value="Write"/>
<s:enumeration value="Delete"/>
<s:enumeration value="AllAccess"/>
</s:restriction>
</s:simpleType>
Therefore, on the client UserRights.AllAccess lost its relationship to other user right values. On the server expression (UserRights.AllAccess & UserRights.Read) != 0
is true, while on the client it is false.
This can lead to disastrous consequences.
Out-Of-Range Values Cause Exception on Receiving End
The following server-side code:
enum Test
{
SomeValue = 1
}
[WebMethod]
public Test GetValue()
{
return (Test)512;
}
will cause "invalid XML document" exception on the client side when reading GetValue() response. This exception is related to how XML serializer works with enums. "Legal" values are transmitted as text. E.g. value of 1 would be transmitted as <Test>SomeValue</Test>. For [Flags] enums multiple text strings are transmitted to indicate concatenation of several masks, e.g. <UserRights>Read Write</UserRights>. However, out-of-range values are transmitted as stringified integers, e.g. <Test>512</Test>. These integers are not understood at the receiving end and cause exception.
Controlling Generated XML
It seems that .NET framework does not give you much leeway in controlling XML generated for enums. In particular, constructs like :
[XmlElement(typeof(int))]
enum MyEnum
{
...
}
or
[XmlElement(DataType="integer")]
enum MyEnum
{
...
}
do compile, but fail miserably at run-time.
One useful attribute is [XmlEnum], which allows to change names of enum members. As we mentioned before, enum members are transmitted as literal strings. Therefore, if one has flags enum like this:
[Flags]
enum MyMask
{
VeryVeryLongFlagNameWillBeTransmittedToClient,
AnotherQuiteLongFlagNameAlongTheFirstOne,
EtCeteraEtCetera
}
generated XML can get quite verbose. To prevent this, transmitted literal strings may be changed using [XmlEnum]:
[Flags]
enum MyMask
{
[XmlEnum("VeryLong")] VeryVeryLongFlagNameWillBeTransmittedToClient,
[XmlEnum("Another")] AnotherQuiteLongFlagNameAlongTheFirstOne,
[XmlEnum("EtCetera")] EtCeteraEtCetera
}
Conclusion
Extra caution must be excercised when transmitting enums over web service boundary. Behavior of XML serializer is not always straightforward for enums, and sometimes can cause serious incompatibilities between client and server. To ensure correct operation of software, one must keep in mind its limitations. If numeric values need to be preserved across the wire, they must be transferred as integers, not enums. In this case, however, client must have ad-hoc knowledge regarding what value means what.
.NET framework provides limited means of manipulating XML generated for enums. In particular, we were unable to find an attribute that would allow to automatically transmit enum as int.
Web Services and C# Enums -摘自网络的更多相关文章
- Web Services and C# Enums
Web Service Transparency .NET support for web services is excellent in creating illusion of transpar ...
- Google Maps API Web Services
原文:Google Maps API Web Services 摘自:https://developers.google.com/maps/documentation/webservices/ Goo ...
- RESTful Web Services初探
RESTful Web Services初探 作者:杜刚 近几年,RESTful Web Services渐渐开始流行,大量用于解决异构系统间的通信问题.很多网站和应用提供的API,都是基于RESTf ...
- (转) Web 建站技术中,HTML、HTML5、XHTML、CSS、SQL、JavaScript、PHP、ASP.NET、Web Services 是什么?
Web 建站技术中,HTML.HTML5.XHTML.CSS.SQL.JavaScript.PHP.ASP.NET.Web Services 是什么? 建站有很多技术,如 HTML.HTML5.XHT ...
- Web Services 中XML、SOAP和WSDL的一些必要知识
Web Services 是由xml来定义数据格式的,通过SOAP协议在各个系统平台中传输,那么接下来讨论下SOAP和WSDL的各自作用. SOAP和WSDL对Web Service.WCF进行深入了 ...
- 跟我一起学WCF(3)——利用Web Services开发分布式应用
一.引言 在前面文章中分别介绍了MSMQ和.NET Remoting技术,今天继续分享.NET 平台下另一种分布式技术——Web Services 二.Web Services 详细介绍 2.1 We ...
- 【转】RESTful Web Services初探
近几年,RESTful Web Services渐渐开始流行,大量用于解决异构系统间的通信问题.很多网站和应用提供的API,都是基于RESTful风格的Web Services,比较著名的包括Twit ...
- Android:控件WebView显示网页 -摘自网络
WebView可以使得网页轻松的内嵌到app里,还可以直接跟js相互调用. webview有两个方法:setWebChromeClient 和 setWebClient setWebClient:主要 ...
- 基于Spring设计并实现RESTful Web Services(转)
基于Spring设计并实现RESTful Web Services 在本教程中,你将会使用Spring来创建一个具有生产力的RESTful网络服务. 为什么用RESTful网络服务? 从和Amazon ...
随机推荐
- jexus 启动失败 原因定位
现象: root@test:/usr/jexus/siteconf# /usr/jexus/jws restartRestarting ... Failure 定位步骤: 1.查看/usr/jexus ...
- 肾果手机App Store切换区域(无需Visa或者万事达)
8月份在肾果官网买了个touch6,有时候需要换区去墙外下载app,然而一个个国家都要输入Visa或者万事达卡...今天终于找到一个不用输入信用卡号的区域:Canada!!! 办法(适用于8.X,7. ...
- BT5之网络配置
输入ifconfig命令,可以查看当前IP地址设置情况.查看路由表的命令(用来检查默认网关是否设置正确):netstat -r 一.让BT5自动获取IP地址 自动获取IP地址,使用dhclient命令 ...
- size_t为何这么重要?
原文Why size_t matters 合理的使用size_t可以提高程序的可移植性和代码的可读性,让你的程序更高效. Numerous functions in the Standard C li ...
- 执行gem install dryrun错误
ERROR: While executing gem ... (Gem::FilePermissionError) You don't have write permissions for ...
- 引用计数(retainCount)
ClassA.h: #import <Foundation/Foundation.h> @interface ClassA:NSObject { NSString *name; } -(v ...
- C语言中的宏总结
宏定义分为两种: 1.变量式宏定义,如 #define abc def #define str "string" #define num 100 2.函数式宏定义, #define ...
- tshark 使用说明
yum install -y wireshark 最近才发现,原来wireshark也提供有Linux命令行工具-tshark.tshark不仅有抓包的功能,还带了解析各种协议的能力.下面我们以两个实 ...
- logstash gsub替换
{ "message" => "192.168.11.186,192.168.11.187\t48391,3306\tDec 7, 2016 13:26:25.13 ...
- plsql 高效原则
sql优化是项复杂的工作,不能简单而论,但是在平时书写脚本时的一些细节可以大大提高我们编写代码的效率,提高代码质量. 以下这些规则部分是我的经验,部分是网络资料,整理后在我平时的工作中运用后得到验证的 ...