WCF响应返回为text/html,而不是xml

WCF响应返回为text/html,而不是xml,wcf,Wcf,我认为序列化一定有问题。我的班级是: [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, ...) {

我认为序列化一定有问题。我的班级是:

[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;
    }
}
生成的源:

<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>
00

它不会在页面上显示xml,因为它说响应类型是text/html。有什么想法吗?

您使用什么类型的客户端来调用web服务

你可以试试

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

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

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

当您将格式值传递为Json时,您正在将传出响应格式设置为Json

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

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

我使用的是自动格式选择:它取决于客户端发送的HTTP请求。看,我只是在浏览器中访问它。请求头显示:Accept:text/html、application/xhtml+xml、application/xml;q=0.9,/;q=0.8浏览器以最高优先级请求
text/html
,并从您的WCF服务接收
text/html
。这就是
automaticFormatSelectEnabled
应该做的事情。如果您不希望出现这种行为,您需要禁用它或告诉您的客户机,它应该请求
应用程序/xml
(就像AJAX请求一样)。@Gene,我认为问题在于WCF将响应序列化为xml,但指示HTML的内容类型。没有适合HTML的格式化程序,因此自动格式选择行为应该选择下一个最合适的accept标头值,即XML。我使用的是自动格式选择:它正在生成XML,只是由于某种原因响应类型不正确。
WebOperationContext.Current.OutgoingResponse.Format = WebMessageFormat.Json;