WCF WebInvoke ResponseFormat

前提是你 提交于 2019-12-01 03:58:32

问题


I have a WCF restul service and I want to allow the user to choose what request format they want, i have the decorations

    [OperationContract]
    [WebInvoke(Method = "GET", 
        ResponseFormat = WebMessageFormat.Xml, 
        BodyStyle = WebMessageBodyStyle.Wrapped, 
        UriTemplate = "getstreamurl?ch={ch}&format=xml")]
    [WebInvoke(Method = "GET",
        ResponseFormat = WebMessageFormat.Json,
        BodyStyle = WebMessageBodyStyle.Wrapped,
        UriTemplate = "getstreamurl?ch={ch}&format=json")]

First of, is there a way to specify the ResponseFormat at runtime and take the format in as an argument to the method? From reading around i dont think so... OK next thing The above code is ok and works, but im having a problem, i want to be able to specify a default, so when no format arguement is passed then i just default but if i decorate like so

    [WebInvoke(Method = "GET", 
        ResponseFormat = WebMessageFormat.Xml, 
        BodyStyle = WebMessageBodyStyle.Wrapped, 
        UriTemplate = "getstreamurl?ch={ch})]

    [OperationContract]
    [WebInvoke(Method = "GET",
        ResponseFormat = WebMessageFormat.Json,
        BodyStyle = WebMessageBodyStyle.Wrapped,
        UriTemplate = "getstreamurl?ch={ch}&format=json")]

Where the XML is the default, if i try to call the service method through the browser it tells me that:

UriTemplateTable does not support multiple templates that have equivalent path as template 'getstreamurl?ch={ch}' but have different query strings, where the query strings cannot all be disambiguated via literal values. See the documentation for UriTemplateTable for more detail

They obviously can be distinguished but it seems that WCF is only reading up to the argument and thats it...Any suggestions?


回答1:


No, I don't think you can do that programmatically at runtime. What you can do of course if to expose two distinct endpoints from your service - one returning XML, another returning JSON, and then programmatically pick which one to call from your client app.

Marc

Update: as Steve Michelotti correctly points out, this automatic switching between JSON and XML can now be achieved in WCF 4.0. WCF 4.0 has an improved REST support which also includes an Format Message Selection feature, based on HTTP accept headers.

For more info on WCF 4.0's new features, see: A Developer's Introduction to WCF 4.0




回答2:


You can do this if your rest service is configured automatically select response type.

Then on client request simply add needed header Accept: application/json



来源:https://stackoverflow.com/questions/1008706/wcf-webinvoke-responseformat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!