Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return html from wcf service

I have a web service from which I need to return a string containing html. This html is the markup for a Select control (for use in jqGrid search filters), e.g.

<select><option id='1'> value 1 </option></select>  

My WCF web service contains a method that returns this value as a string...

public string GetLeadTypeSelect()
{
    return "<select><option id='1'> value 1 </option></select>";
}  

and the contract for this method is :

[OperationContract]
[WebInvoke(Method = "GET",
    BodyStyle = WebMessageBodyStyle.Bare,
    ResponseFormat = WebMessageFormat.Json)]
string GetLeadTypeSelect();  

My problem is that escape characters are inserted into the string so rendering the returned HTML useless - the service returns this :

"<select><option id='1'> value 1 <\/option><\/select>"  

The quotation marks and the escaped '/' in the closing <option> and <select> tags both cause problems.

jqGrid uses the returned HTML to display the dropdown...

filterModel: [
    { label: 'Type', name: 'type', stype: 'select', surl: '../../../Services/Leads/GetLeads.svc/GetLeadTypeSelect' },

So, my question is, how to I return pure HTML back to the client from this web service so that it can be inserted into my HTML page?

Thanks in advance for any help, Colin.

like image 952
Col Avatar asked Jan 07 '10 10:01

Col


1 Answers

I know this is an old post, but for a service that will only be hosted in IIS, here is an easy way to return html:

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
public Stream getHtml()
{
    // get the html
    var html = DoSomethingToGetHtml();  //Not a built-in .Net method ;)

    // we want our result interpreted as plain html
    WebOperationContext.Current.OutgoingResponse.ContentType = "text/html; charset=utf-8";

    // create a stream from our html because trying to return a string adds an extra header tag
    //      to the response.  Returning a stream returns the html by itself
    var result = new MemoryStream(Encoding.UTF8.GetBytes(html));

    // return the result
    return result;
}

This code requires the following in the web.config hosting the service:

<system.serviceModel>
    <!-- enable HttpContext.Current by setting aspNetCompatibilityEnabled=true-->
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>

    <behaviors>
        <endpointBehaviors>
            <behavior name="webHttpEnabled">              
                <webHttp/>
            </behavior>
        </endpointBehaviors>
    </behaviors>
    ...
<system.serviceModel>

In the configuration for the service, set behaviorConfiguration="webHttpEnabled".

Returning html in this way limits the reusability of the service a bit, but it's an easy way to solve the problem if you're reasonably sure the service will always be hosted in IIS.

like image 113
tiggercm Avatar answered Nov 09 '22 00:11

tiggercm