【问题标题】:How to call self host wcf service from asp.net client?如何从 asp.net 客户端调用自主机 wcf 服务?
【发布时间】:2013-06-17 04:06:38
【问题描述】:

我有一个自己托管 WCF 服务的控制台应用程序。当用户访问 asp.net 应用程序并单击页面上的按钮时,如何编写一些脚本来调用这个自托管的 WCF 服务(本地托管的服务)。我猜我的脚本有问题,请帮忙。

namespace SelfHost
{
  [ServiceContract]
  public interface IHelloWorldService
  {
      [OperationContract]
      string SayHello(string name);
  }

  [AspNetCompatibilityRequirements(RequirementsMode =     AspNetCompatibilityRequirementsMode.Allowed)]
  public class HelloWorldService : IHelloWorldService
  {
    public string SayHello(string name)
    {
        return string.Format("Hello, {0}", name);
    }
}

class Program
{
    static void Main(string[] args)
    {
        Uri baseAddress = new Uri("http://127.0.0.1/hello");

        // Create the ServiceHost.
        using (ServiceHost host = new ServiceHost(typeof(HelloWorldService), baseAddress))
        {
            // Enable metadata publishing.
            ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
            smb.HttpGetEnabled = true;
            smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
            host.Description.Behaviors.Add(smb);

            // Open the ServiceHost to start listening for messages. Since
            // no endpoints are explicitly configured, the runtime will create
            // one endpoint per base address for each service contract implemented
            // by the service.
            host.Open();

            Console.WriteLine("The service is ready at {0}", baseAddress);
            Console.WriteLine("Press <Enter> to stop the service.");
            Console.ReadLine();

            // Close the ServiceHost.
            host.Close();
        }
    }
}

调用服务的脚本

<script type="text/javascript">
    function invokeService() {
        $(document).ready(function () {
            var userName = " test";

            $.ajax({
                type: "POST",
                async: "false",
                url: "http://127.0.0.1:8080/hello",
                data: "{'name':'" + userName + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                processData: true,
                method: "SayHello",
                success: function (result) {
                    AjaxSucceeded(result);
                },
                error: function (retult) {
                    AjaxFailed(result);
                }
            });
        });
    }

【问题讨论】:

  • 我们需要查看您的自托管服务的配置文件!这就是配置绑定和行为等所有有趣的东西的地方 - 没有它,我们真的无能为力......但是调用自托管的 WCF 服务与调用 IIS 托管的 WCF 服务没有什么不同,真的 - 只需获取 WCF 的 ABC 正确(地址、绑定、合同),您就可以开始了!
  • 当您尝试调用服务时,控制台应用程序是否正在运行?
  • 从您的 WCF 服务看来,您正在使用 BasicHttpBinding 公开一个 SOAP 服务。如果您想从 JQuery/Ajax 调用您的服务而不是在您的 JQuery/Ajax 中构建完整的 SOAP 消息,那么最好使用 WebHttpBinding 公开 WCF 服务
  • 通过 chrome 调试,似乎从脚本调用本地自托管服务是跨域的,我会尝试解决。

标签: c# jquery wcf console-application


【解决方案1】:

不希望以这种方式使用 jquery 调用 WCF 服务。

最大的问题是您暴露了一个 Soap 服务 并试图使用 rest-like 客户端

从 .net 3.5 开始,WCF 允许您将 WCF 服务操作公开给非 SOAP 端点。您必须以这种方式公开您的服务才能使用 Jquery 消费它。

MSDN的起点即here,几年前msdn magazine有很好的介绍。

一个非常简单的例子是(没有任何配置)

[ServiceContract]
public interface IService
{
    [OperationContract]
    [WebGet(BodyStyle=WebMessageBodyStyle.Bare, RequestFormat=WebMessageFormat.Json, ResponseFormat=WebMessageFormat.Json)]
    string EchoWithGet(string s);

    [OperationContract]
    [WebInvoke(BodyStyle=WebMessageBodyStyle.Bare, RequestFormat=WebMessageFormat.Json, ResponseFormat=WebMessageFormat.Json)]
    string EchoWithPost(string s);
}

public class Service : IService
{
    public string EchoWithGet(string s)
    {
        return "You said " + s;
    }

    public string EchoWithPost(string s)
    {
        return "You said " + s;
    }
}

class Program
{
    static void Main(string[] args)
    {
        WebServiceHost host = new WebServiceHost(typeof(Service), new Uri("http://localhost:8000/"));
        ServiceEndpoint ep = host.AddServiceEndpoint(typeof(IService), new WebHttpBinding(), "");
        ServiceDebugBehavior sdb = host.Description.Behaviors.Find<ServiceDebugBehavior>();
        sdb.HttpHelpPageEnabled = false;
        host.Open();
        Console.WriteLine("Service is running");
        Console.WriteLine("Press enter to quit...");
        Console.ReadLine();
        host.Close();
    }
}

【讨论】:

    【解决方案2】:

    刚发现不允许通过脚本进行跨域调用。所以另一种方法是有一个命令行应用程序或控制台文件来调用 wcf 服务。然后在注册表中注册这个应用程序。然后从脚本启动应用程序。

    【讨论】:

      猜你喜欢
      • 2012-11-27
      • 1970-01-01
      • 2016-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多