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 ...
随机推荐
- UML_时序图画法
UML建模之时序图(Sequence Diagram) 一.时序图简介(Brief introduction) 二.时序图元素(Sequence Diagram Elements) 角色(Actor) ...
- python eval函数
eval()函数十分强大,官方demo解释为:将字符串str当成有效的表达式来求值并返回计算结果. 可以把字符串转为list.tuple .dict 等数据类型 1.把字符串转为字典 ####### ...
- Vases and Flowers
hdu4614:http://acm.hdu.edu.cn/showproblem.php?pid=4614 题意:给你n个花瓶,然后有两种操作:1从a开始选择b个花瓶,放进花,输出左端点,右端点 2 ...
- Percona Xtrabackup备份mysql全库及指定数据库(完整备份与增量备份)
原文地址:http://www.tuicool.com/articles/RZRnq2 Xtrabackup简介 Percona XtraBackup是开源免费的MySQL数据库热备份软件,它能对In ...
- ANDROID_MARS学习笔记_S02_003_AutoCompleteTextView
一. public class CountriesActivity extends Activity { protected void onCreate(Bundle icicle) { super. ...
- Android中改变dialog的显示的位置和大小
private void setDialogSize(Dialog dg) { Window dialogWindow = dg.getWindow(); WindowManager.LayoutPa ...
- Form.KeyPreview 属性2
在使用.Net Framework编写窗体应用程序的时候,有时有需要响应窗体的按键消息. 当窗体上没有任何其他控件的时候,窗体是可以直接响应这些消息的. 但是当窗体上有其他控件时,会发现窗体再也不会响 ...
- Centos4.3安装MySQL-python-1.2.3,出现error: command 'gcc' failed with exit status 1
在Linux Centos 4.3上安装MySQL-python-1.2.3的时候出现error: command 'gcc' failed with exit status 1, 具体原因是因为没有 ...
- C#实现微信公众号群发消息(突破破解一天只能发一次的限制)
总体思路:1.首先必须要在微信公众平台上申请一个公众号. 2.然后进行模拟登陆.(由于我对http传输原理和编程不是特别懂,在模拟登陆的地方,不是特别清楚,希望有大神指教) 3.模拟登陆后会获得一个t ...
- ora-01589
今天遇到了ORA-01589这个错误,下面把解决方案记录如下: SQL*Plus: Release 9.2.0.1.0 - Production on 星期四 4月 17 15:01:26 2008C ...