从javascript调用Winform托管的WCF服务

问题描述:

我有一个带有Ajax Web端点的Winform托管WCF服务.

I have a Winform hosted WCF service with Ajax Web endpoint.

我还单独拥有一个ASP.NET项目,页面上带有ScriptManager组件.

I also have an ASP.NET project separately, with ScriptManager component on the page.

我的问题是,如果我使用JavaScript从ASP.NET应用程序的客户端对Winform托管服务进行服务调用,那应该可行吗?

My question is, should that work if I make service calls to my Winform hosted service from the client side of ASP.NET app using javascript?

我的ASP.NET默认页面如下:

My ASP.NET Default page looks like this:

<script type="text/javascript">    
function Button1_onclick() {        
// ????How to call a service method?????    
}
</script>

<asp:ScriptManager ID="ScriptManager1" runat="server">
    <Services>
           <asp:ServiceReference Path="http://localhost:8000/web" />  //My winform hosted service
    </Services>
</asp:ScriptManager>

还是我必须将服务托管在IIS中才能被AJAX使用?

Or do I have to host my service in IIS to be consumable by AJAX?

事实证明,使用正确的服务配置非常简单:

It turned out to be pretty simple with the right service configuration:

<endpoint address="Web/" binding="webHttpBinding" contract="IMyService"  
          behaviorConfiguration="WebBehavior"/>
<!-- ... -->
<endpointBehaviors>
    <behavior name="WebBehavior">
        <webHttp defaultOutgoingResponseFormat="Json" defaultBodyStyle="Wrapped" />
    </behavior>
</endpointBehaviors>

我还在服务合同上添加了WebInvoke属性:

I also added a WebInvoke attribute on my service contract:

[WebInvoke(Method = "POST")]
public interface IMyService {
    // ...
}

使用此配置,您可以仅使用浏览器来调用服务方法.因此,javascript只需要对URL进行POST HTTP查询,这是一项琐碎的任务,不需要任何ASP.NET ServiceManager东西. jQuery示例:

With this configuration you can make a call to the service method just using your browser. So javascript only has to make a POST HTTP query to the url, that's a trivial task that doesn't require any ASP.NET ServiceManager stuff. jQuery sample:

<script type="text/javascript"> 
function Button1_onclick() {        
    $.ajax({
        type: "POST",
        url: "http://localhost:8000/web/",
        data: "",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        processdata: true
        success: function(msg) { /*...*/ },
        error: /*..error handler..*/
    });
}
</script>

就我而言,我不必将任何参数传递给服务(实际上,我的方法被标记为单向方法).但是添加参数只会使事情复杂一点(您将传入json字符串而不是将空字符串作为数据).

In my case I didn't have to pass any parameters to the service (in fact, my method is marked as a one way method). But adding parameters would only complicate things a bit (you would to pass a json string in instead of an empty string as a data).