从wcf服务返回html

Col*_*Col 5 html wcf json jqgrid

我有一个Web服务,我需要从中返回一个包含html的字符串.这个html是Select控件的标记(用于jqGrid搜索过滤器),例如

<select><option id='1'> value 1 </option></select>  
Run Code Online (Sandbox Code Playgroud)

我的WCF Web服务包含一个将此值作为字符串返回的方法...

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

这种方法的合同是:

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

我的问题是转义字符被插入到字符串中,因此渲染返回的HTML无用 - 服务返回:

"<select><option id='1'> value 1 <\/option><\/select>"  
Run Code Online (Sandbox Code Playgroud)

引号和'/'关闭<option><select>标签中的转义都会导致问题.

jqGrid使用返回的HTML显示下拉列表...

filterModel: [
    { label: 'Type', name: 'type', stype: 'select', surl: '../../../Services/Leads/GetLeads.svc/GetLeadTypeSelect' },
Run Code Online (Sandbox Code Playgroud)

所以,我的问题是,如何将纯HTML从此Web服务返回给客户端,以便将其插入到我的HTML页面中?

科林,提前感谢您的帮助.

tig*_*rcm 6

我知道这是一个旧帖子,但对于只在IIS中托管的服务,这里有一个简单的方法来返回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;
}
Run Code Online (Sandbox Code Playgroud)

此代码在托管服务的web.config中需要以下内容:

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

    <behaviors>
        <endpointBehaviors>
            <behavior name="webHttpEnabled">              
                <webHttp/>
            </behavior>
        </endpointBehaviors>
    </behaviors>
    ...
<system.serviceModel>
Run Code Online (Sandbox Code Playgroud)

在服务配置中,设置 behaviorConfiguration="webHttpEnabled".

以这种方式返回html会限制服务的可重用性,但如果您有理由确定该服务将始终在IIS中托管,那么这是解决问题的简单方法.


Sna*_*ake 0

我假设你通过 Javascript 使用它。

如果您执行 unescape(response),您的问题应该得到解决。

另一方面,如果您不在 Javascript 中使用它,而只是在 ASP.NET / PHP / 任何网站中使用它,那么您最好只返回一个值数组并显示值,这样您就可以在其他代码。

您的代码现在只能在 HTML 环境中运行。如果您明天需要编写一个 .NET/C++/任何使用您的 Web 服务的应用程序怎么办?那么你需要改变它。这不是网络服务的重点。Web 服务促进代码的可重用性。而你正在反对这一点。(代码将会获胜!)