如何基于xsd文件创建一个接收和发送xml的web服务?

问题描述:

我需要创建一个接受 xml 的 .NET Web 服务,使用它来查询数据库,然后返回 xml.我已经获得了请求和响应的 xsd 文件.有人能指出我从哪里开始或举个例子的正确方向吗?

I need to create a .NET web service that accepts xml, uses this to query a database, and then returns xml. I have been given xsd files for the request and response. Could someone point me in the right direction for where I start from or an example?

我之前没有使用过 WCF,所以更喜欢使用简单的 asmx 文件来执行此操作.我知道如何从数据库中获取数据,所以我丢失了 xml 和 web 服务位.

I haven't used WCF before so would prefer to use a simple asmx file to do this. I know how to get the data from the database, so it's the xml and web service bits where I'm lost.

我已经尝试在谷歌上搜索了一段时间,但不知道从哪里开始.谢谢.

I've tried googling this for a while but don't know where to start. Thanks.

您遇到的问题是 asmx 和 WCF 都是代码优先 Web 服务技术.这意味着您通常从类开始,而 Web 服务堆栈负责通过网络将您的类型公开为 XML.

The problem you have is that asmx and WCF are both code-first web service technologies. What this means is that you generally start with classes and the web service stack takes care of exposing your types as XML across the wire.

您从一个架构开始,它不是代码.因此,如果您想使用 asmx/wcf,您需要在代码中为您的架构建模.您可以通过使用 xsd.exe(或用于 WCF 的 svcutil.exe)从您的架构推断类结构来完成此操作.

You are starting with a schema, which is not code. So if you want to use asmx/wcf you need to model your schema in code. You can do this by inferring a class structure from your schema using xsd.exe (or svcutil.exe for WCF).

或者,您可以根据架构定义手动为您的类建模.

Alternatively you can model your classes by hand based on the schema definition.

一旦你有了你的类,你就可以向代码中添加声明性属性(参见 http://msdn.microsoft.com/en-us/library/83y7df3e.aspx 用于 asmx,DataContractDataMember 用于 WCF).这些属性控制:

Once you have your classes then you can add declarative attributes to the code (See http://msdn.microsoft.com/en-us/library/83y7df3e.aspx for asmx, DataContract and DataMember for WCF). These attributes control:

  1. 收到服务请求时如何将传入的 XML 流反序列化为类型,以及
  2. 当您的响应类型的实例从您的服务传出时如何序列化为 XML

这种方法的问题在于,让您的 XML 根据您的 XSD 模式进行验证会有点失败,因为您不能 100% 依赖来自 XSD 的类推断,此外,如果您正在手工建模.

The problem with this approach is that getting your XML to validate against your XSD schemas will be a little bit hit and miss, as you cannot rely 100% on class inference from XSD, and additionally you may miss some fine detail if you are modelling it by hand.

无论采用哪种方式,您都需要确保您的请求和响应类实例干净利落地序列化为 XML,这将根据您提供的 XSD 架构进行验证.

Whichever way you do it you need to make sure that your request and response class instances cleanly serialize into XML which will validate against the XSD schemas you have been given.

另请看一个名为 WSCF-Blue 的框架,它允许您进行契约优先 Web 服务设计:http://wscfblue.codeplex.com/

Also look at a framework called WSCF-Blue which allows you to do contract-first web service design: http://wscfblue.codeplex.com/

祝你好运,如果你需要更多细节,请通过评论告诉我.

Good luck, if you need any more detail about this please let me know via a comment.