return html from wcf service

前端 未结 2 1670
逝去的感伤
逝去的感伤 2021-01-03 03:17

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.



        
相关标签:
2条回答
  • 2021-01-03 03:45

    I assume you use it through Javascript.

    If you do an unescape(response), your problem should be solved.

    On the other hand, if you don't use it in Javascript but just in a ASP.NET / PHP / whatever website you are probably better off by just returning an array of values and display values, so that you can reuse the webservice in other code.

    Your piece of code now only works in an HTML environment. What if you need to write a .NET / C++ / whatever app tomorrow that utilizes your webservice? Then you'll need to change it. And that is not the point of webservices. Webservices promote reusability of code. And you are fighting against that. (and the code will win!)

    0 讨论(0)
  • 2021-01-03 03:46

    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.

    0 讨论(0)
提交回复
热议问题