2009-06-08 67 views
0

我刚刚开始使用REST入门工具包,并且尝试构建自己的服务时遇到了障碍。我试图创建一个帐户管理服务,我不能让服务序列化我的对象,抛出了以下错误:无法反序列化WCF REST服务中的XML

Unable to deserialize XML body with root name 'CreateAccount' and root namespace '' (for operation 'CreateAccount' and contract ('Service', ' http://tempuri.org/ ')) using DataContractSerializer. Ensure that the type corresponding to the XML is added to the known types collection of the service.

下面是该服务的实际代码(基于关闭的“与该项目来到DoWork的”法):

[WebHelp(Comment = "Creates a Membership account")] 
[WebInvoke(UriTemplate = "CreateAccount", RequestFormat = WebMessageFormat.Xml)] 
[OperationContract] 
public ServiceResponse CreateAccount(CreateAccount request) 
{ 
    try 
    { 
     // do stuff 

     return new ServiceResponse() 
     { 
      Status = "SUCCESS", 
      ErrorMessage = "" 
     }; 
    } 
    catch (Exception ex) 
    { 
     return new ServiceResponse() 
     { 
      Status = "ERROR", 
      ErrorMessage = ex.Message + "\n\n" + ex.StackTrace 
     }; 
    } 
} 

而且最后但并非最不重要的,这里是造成所有的麻烦对象:

public class CreateAccount 
{ 
    public string FirstName { get; set; } 
    public string LastName { get; set; } 
    public string Email { get; set; } 
    public bool SignUpForNewsletter { get; set; } 
    public string Password { get; set; } 
} 

我错过了什么傻?

在此先感谢!

回答

4

看来问题是您的方法名称“CreateAccount”和您的输入类型“CreateAccount”之间的命名空间冲突。

而且,你必须标记你的createAccount类型作为DataContract像这样:

[DataContract] 
public CreateAccount 
{ 
    [DataMember] 
    public string LastName { get; set; } 

    ... 
} 

如果你想保持相同的名称,你可以指定的createAccount类命名空间。

我注意到你也有返回类型。确保返回类型也用DataContract属性标记。此外,指定返回格式像这样:

ResponseFormat = WebMessageFormat.Xml 
+0

我刚想到可能与对象和方法的命名冲突。我已将对象名更改为'CreateAccountRequest',并添加了[DataContract]和[DataMember]属性,但没有运气。 – 2009-06-08 21:09:01

+0

请参阅上面的编辑。确保您也在服务合同上指定了属性。你应该有一个服务界面。这就是OperationContract和WebInvoke属性应该存在的地方。 – Doanair 2009-06-08 21:25:18

1

如果您还没有它,我认为您的CreatAccount类上方有[DataContract]属性。

7

原来我错过了在业务对象上[DataContract]属性的额外的价值。

应该[DataContract(Namespace = "")]

0

我也有类似的问题,但我确实有DataContract属性。当我尝试将xml读回到对象时,我所缺少的是来自根元素的xmlns =“http://uri.org”属性。
例如

<Root_Element xmlns="http://uri.org"><Child_Element/>...</Root_Element>