xml - WCF 4.0 Rest 服务设置内容类型

标签 xml wcf json content-type

我刚刚完成我的第一个 WCF 4.0 Rest 服务,但不明白为什么返回数据的内容类型在通过 Fiddler 和 Firefox 调用服务之间会发生变化。这是我的服务契约(Contract):

[ServiceContract]
public interface IProjectService
{
    [OperationContract]
    [WebGet(UriTemplate = "project/{id}/json", BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json)]
    ProjectDataContract GetProjectJson(string id);

    [OperationContract]
    [WebGet(UriTemplate = "project/{id}/xml", BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Xml)]
    ProjectDataContract GetProjectXml(string id);

    [OperationContract]
    [WebGet(UriTemplate = "userprojects/{userKey}/json", BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json)]
    List<ProjectDataContract> GetProjectsByUserJson(string userKey);

    [OperationContract]
    [WebGet(UriTemplate = "userprojects/{userKey}/xml", BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Xml)]
    List<ProjectDataContract> GetProjectsByUserXml(string userKey);
}

如您所见,我正在为每个操作设置响应格式。如果请求以“/json”结尾,那么我将返回 json 数据。如果请求以“/xml”结尾,则返回 xml 数据。至少那是我的意图。

当我调用 http://localhost:5050/ProjectServiceLibrary/project/27/xml 时在 Firefox 中,我可以看到内容类型设置为“text/html”,而在 fiddler 中调用的相同请求显示正确的内容类型“application/xml”。调用带有“/json”后缀的请求 - 在 firefox 中为“text/html”,在 fiddler 中为“application/json”。

那么,为什么会这样呢?我信任哪一个?我下载了 JSONView Firefox 附加组件,但这让一切看起来都像 json。它将 XML 视为 JSON。

我确定我遗漏了一些明显的东西。任何帮助将不胜感激。

最佳答案

这与客户端发送的请求中的Accept头有关。 Accept header 包含 MIME 类型的优先列表。接受 header 由客户端(Firefox、Fiddler)定义,并告诉服务器它能够接收哪些内容类型。服务器将根据优先级和兼容性使用最佳匹配。

FireFox 生成的接受 header 赋予 text/html 更高的优先级 - 告诉服务器在可能的情况下发送 text/html。您可能会发现 Fiddler 做的恰恰相反,给予 application/xml 更高的优先级 - 这解释了您所看到的。

Kris Jordans blog 上有关于请求 header 的更多详细信息.

关于xml - WCF 4.0 Rest 服务设置内容类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4822190/

相关文章:

java - 严重 : Error configuring application listener of class org. apache.struts2.tiles.Struts Tiles Listener java.lang.NoClassDefFoundError

android - 如何更改ListPreference标题的颜色?

wcf - 优雅地终止 WCF 服务 - 完成所有打开的 session 并限制新 session

.net - 远程管理和数据捕获 : WCF, SQL Sync、SyncFramework、BITS 还是其他?

javascript - 在页面之间传递JavaScript变量可以正常工作,但是DataTables仍然会出错

javascript - 如何突出显示单击链接的相应标题?

c# - 无法将类型 System.Collections.ObjectModel.ObservableCollection<> 隐式转换为 System.Collections.Generic.List<>

c# - 将 C# 对象序列化为 JSON 时如何处理不同的命名约定?

json - 避免使用从表行构建的 JSON 中的匿名字段

java - Android:Simple XML SAX Parser-一遍又一遍地显示相同的数据