是否可以在Asp.Net Web服务中迭代循环

时间:2014-02-10 10:43:00

标签: c# asp.net web-services

我有一个控制台应用程序,我在其中使用asp.net webservice.Also,我在我的服务中声明了一个显示方法,它接受并迭代一个字符串数组。但是,当我执行控制台应用程序时,它显示为空控制台窗口。为什么没有显示数组内容?

使用以下服务的代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace usingWebServiceExample
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] arr = new string[3] {"harry","ronn","sheldon" };
            localhost.Service service = new localhost.Service();
            service.display(arr);
            Console.Read();
        }
    }
}

服务代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
// [System.Web.Script.Services.ScriptService]

public class Service : System.Web.Services.WebService
{
    public Service()
    {

    }

    [WebMethod]
    public void display(string[] arr)
    {
        for (int i = 0; i < arr.Length; i++)
        {
            Console.WriteLine(arr[i]);
        }
    }

}

3 个答案:

答案 0 :(得分:4)

对于asp.net,您可能需要使用System.Diagnostics.Debug.WriteLine(...)而不是Console.WriteLine(),并且您可以在视觉工作室的output窗口中看到结果。

写入日志可能没有多大意义,您可以使用string.Join

返回数组
public string display(string[] arr)
{
    return Join(",", arr)
}

答案 1 :(得分:3)

WebMethod在服务器上运行而不是在您的控制台应用程序上运行,因此编写Console.WriteLine()将写入Web项目的控制台 - 而不是应用程序的。

如果您查看输出窗口,我怀疑您会看到那里打印的值。

为了在控制台窗口中输出文本,您需要从WebMethod返回一个字符串并将其写在应用程序中。

答案 2 :(得分:1)

您需要返回一个字符串数组以打印到客户端,或者使用双工绑定并在客户端实现回调以将消息打印到控制台。

以下是双工回调实现示例: 服务器:

[ServiceContract(CallbackContract=typeof(IConsoleCallback))]
public interface IService1
{

    [OperationContract(IsOneWay = true)]
    void Display(string[] arr);
}

public interface IConsoleCallback
{
    [OperationContract(IsOneWay = true)]
    void WriteLine(string message);
}

public class Service1 : IService1
{
    public void Display(string[] arr)
    {
        var callback = OperationContext.Current.GetCallbackChannel<IConsoleCallback>();

        for (int i = 0; i < arr.Length; i++)
        {
            callback.WriteLine(arr[i]);
        }
    }
}

服务器web.config:

<protocolMapping>
    <add binding="wsDualHttpBinding" scheme="http" />
    <add binding="wsDualHttpBinding" scheme="https" />
</protocolMapping>    

客户端:

class Program
{
    class ConsoleCallback : ServiceReference1.IService1Callback
    {
        public void WriteLine(string message)
        {
            Console.WriteLine(message);
        }
    }


    static void Main(string[] args)
    {
        string[] arr = new string[3] { "harry", "ronn", "sheldon" };
        var service = new ServiceReference1.Service1Client(new InstanceContext(new ConsoleCallback()));
        service.Display(arr);
        Console.Read();
    }
}