开发者

WCF 4.0 Rest Service setting content type

开发者 https://www.devze.com 2023-02-06 22:58 出处:网络
I\'ve just finished my first WCF 4.0 Rest service and don\'t understand why the Content-Type of the data being returned changes between calling the service via Fiddler and Firefox.Here\'s my service c

I've just finished my first WCF 4.0 Rest service and don't understand why the Content-Type of the data being returned changes between calling the service via Fiddler and Firefox. Here's my service 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);
}

As you can see, I'm setting the response format for each operation. If the request ends with "/json" then I'm returning json data. If the request ends with "/xml", then xml data is returned. At least that is what my intentions are.

When I make a call to http://localhost:5050/ProjectServiceLibrary/project/27/xml in Firefox, I can see the content-type is set to "text/html" whereas the same request invoked in fiddler shows the correct content type of "application/xml". Same thing happens for a call to a "/json" suffixed request - "text/html" in firefox and "application/json" in fiddler.

So, why is this happening? Which one do I trust? I downloaded JSONView Firefox add-on, but that makes everything look like json. It treats the XML as JSON.

I'm sure I'm missi开发者_如何学编程ng something obvious. Any help would be greatly appreciated.


This is related to the Accept header in the request sent by the client. The Accept header contains a prioritized list of MIME types. Accept headers are defined by the client (Firefox, Fiddler), and tell the server which content-types it is capable of receiving. The server will use the best match based on priority and compatibility.

Accept headers generated by FireFox give text/html a higher priority - telling the server to send text/html if it is possible. You will probably find that Fiddler does the opposite, giving application/xml the higher priority - this explains what you are seeing.

There's more detailed information about request headers on Kris Jordans blog.

0

精彩评论

暂无评论...
验证码 换一张
取 消