简体   繁体   中英

Calling WCF Server from ASP.NET

I have a simple WCF server that is using DuplexChannelFactory and named pipes. I can call it from a console application and I can call it from a WPF application. However, is it possible to call the same WCF server from ASP.NET and still be able to call it from console\\WPF app?

I am using the following endpoint:

[ServiceContract(SessionMode = SessionMode.Required,
  CallbackContract = typeof(IMyWCFClient))]
public interface IMyWCFServer
{
    [OperationContract]
    bool Subscribe();
    [OperationContract]
    bool UnSubscribe();
}

Can I update this to be callable from ASP.NET?

Yes, you can call WCF service by console, WPF and ASP.NET. But you need to create appropriate endpoint first.

How to: Create a Service Endpoint in Configuration

Basically to create Ajax Enabled endpoint for your wcf service to have ability to call method from javascript you need to perform the following:

1) Adds AspNetCompatibilityRequirements to your WCF service definition, so it will look like in the following code:

namespace Test

[ServiceContract(Namespace = "Test.Services")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class TestService : IMyWCFServer
{
    // To use HTTP GET, add [WebGet] attribute. (Default ResponseFormat is WebMessageFormat.Json)
    // To create an operation that returns XML,
    //     add [WebGet(ResponseFormat=WebMessageFormat.Xml)],
    //     and include the following line in the operation body:
    //         WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";

    public bool UnSubscribe()
    {
        return true;
    }

    public bool Subscribe()
    {
        return false;
    }
}

Note: namespace is also vital, because it will be used by ScriptManager to generated client side proxy after service will be registered in it.

2) Then adds [YourServiceName].svc file with the following definition to Asp.Net web application project:

<%@ ServiceHost 
Language="C#" Debug="true"
Service="Test.TestService " 
Factory="System.ServiceModel.Activation.WebScriptServiceHostFactory" %>

This file enough to register your WCF service as Ajax one.

3) Then register this service with Script Manager by adding the following to pages (or Master page) where you want to use your service:

<asp:ScriptManagerProxy runat="server" ID="ScriptManagerProxy">
    <Services>
        <asp:ServiceReference Path="~/[RelativePathToSVCFile].svc" />
    </Services>
</asp:ScriptManagerProxy>

Then you will be able to call your service from JavaScript like in the following example:

var wasSubscribed = Test.Services.TestService.Subscribe();

Some more information for example can be found in this article: http://dotnetslackers.com/articles/ajax/JSON-EnabledWCFServicesInASPNET35.aspx

EDIT : There are several ways to add script references to script manager programmatically. The first one is ScriptManager control itself can be used too to register wcf service as script service. But to get current instance of script manager you will need reference to current Page Instance. So, the following code shows how this can be done from code behind class of any page or server control:

    protected void Page_Load(object sender, EventArgs e)
    {
        ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page);
        scriptManager.Services.Add(new ServiceReference { Path = "[RelativePathToSVCFile].svc" });
    }

And this is example of how to add ScriptManagerProxy programmatically from code behind class of any page or server control. This approach requires that you have access to controls collection of the page or server control:

    /// <summary>
    /// Called by the ASP.NET page framework to notify server controls that use composition-based implementation to create any child controls they contain in preparation for posting back or rendering.
    /// </summary>
    protected override void CreateChildControls()
    {
        base.CreateChildControls();

        ScriptManagerProxy scriptManagerProxy = new ScriptManagerProxy { ID = "ScriptManagerProxy" };
        this.Controls.Add(scriptManagerProxy);

        scriptManagerProxy.Services.Add(new ServiceReference { Path = "[RelativePathToSVCFile].svc" });
    }

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