2012-02-08 69 views
1

我认为在序列化中一定不能正确。我的班级:WCF响应以text/html格式返回,而不是xml

[DataContract] 
public class User 
{ 
    [DataMember] 
    public int id { get; set; } 
    [DataMember] 
    public string user_id { get; set; } 
    ... 

    public User() { } 

    public User(int id, string user_id, ...) 
    { 
     this.id = id; 
     this.user_id = user_id; 
     ... 
    } 
} 

[DataContract] 
public class UserCollection 
{ 
    [DataMember] 
    public List<User> users { get; set; } 

    [DataMember] 
    public int count { get; set; } 

    [DataMember] 
    public int page { get; set; } 

    public UserCollection() { } 

    public UserCollection(List<User> users, int count, int page) 
    { 
     this.users = users; 
     this.count = count; 
     this.page = page; 
    } 
} 

API调用:

[WebGet(UriTemplate = "?promotion_id={promotion_id}&page={page}&format={format}")] 
    public UserCollection GetAllUsers(string promotion_id, string page, string format) 
    { 
     if (string.Equals("json", format, StringComparison.OrdinalIgnoreCase)) 
      WebOperationContext.Current.OutgoingResponse.Format = WebMessageFormat.Json; 

     UserFactory factory = new UserFactory(); 
     return factory.GetUsersByPromotionID(int.Parse(promotion_id), (int.Parse(page) - 1) * 50, 50); 
    } 

生成的源:

<UserCollection xmlns="http://schemas.datacontract.org/2004/07/API.Library.Resources" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><count>0</count><page>0</page><users/></UserCollection> 

它不显示在页面上的XML,因为它说的响应类型是text/html的。有任何想法吗?

回答

0

您使用什么样的客户端来调用Web服务?

你可以尝试

WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml"; 
+0

我正在使用自动格式选择: 2012-02-08 13:59:43

+0

这取决于客户端发送的HTTP请求。请参阅[WCF Web HTTP格式](http://msdn.microsoft.com/zh-cn/library/ee476510.aspx)。 – Gene 2012-02-08 14:24:06

+0

我只是在浏览器中访问它。请求头文件说: Accept:text/html,application/xhtml + xml,application/xml; q = 0.9,*/*; q = 0.8 – 2012-02-08 14:25:40

0

您是否尝试过加入ResponseFormat = WebMessageFormat.Xml

[WebGet(UriTemplate = "?promotion_id={promotion_id}&page={page}&format={format}", ResponseFormat = WebMessageFormat.Xml)] 
+0

我正在使用自动格式选择: 它生成xml,只是响应类型由于某种原因不正确。 – 2012-02-08 14:01:01

0

当您将格式值作为json传递时,您将输出响应格式设置为Json。

WebOperationContext.Current.OutgoingResponse.Format = WebMessageFormat.Json; 

您是否确定要发送正确的格式参数。还尝试使用Fiddler检查请求和响应。