简体   繁体   中英

How to change a WCF service BodyStyle programmatically?

I have a WCF webservice and it's working pretty cool with some different clients.

Some clients consume it as XML and others as JSON . To have this behavior I've designed all the services, as if they had a extension. If the extension is equal to json , then it return JSON, if not it returns XML.

The code bellow shows how I accomplish this behavior.

    [WebGet(UriTemplate = "test.{PsFormat}")]
    public string test(string PsFormat) {
        DefineResponseFormat(PsFormat);
        return "test";
    }

    public static void DefineResponseFormat(string PsFormat)
    {
        OutgoingWebResponseContext context = WebOperationContext.Current.OutgoingResponse;
        if (PsFormat.ToLower() == "json") {
            context.Format = WebMessageFormat.Json;
            context.ContentType = "application/json; charset=utf-8";
        }
        else if (PsFormat.ToLower() == "wjson") {
            context.Format = WebMessageFormat.Json;
            context.ContentType = "application/json; charset=utf-8";
            // CHANGE BodyStyle TO WRAPPED
        }
        else {
            context.Format = WebMessageFormat.Xml;
            context.ContentType = "text/xml; charset=utf-8";
        }
    }

The problem, is that I've always returned the JSON as if the WebGet Attribute BodyStyle = WebMessageBodyStyle.Bare, that is the default value. And now, I have a new client that need to sonsume it as if BodyStyle = WebMessageBodyStyle.Wrapped. (Represented in the code above in the else if, with the extensions wjson .)

The question is: How do I change the BodyStyle value programmatically?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM