且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将WebService添加到C#WinForm?

更新时间:2023-12-06 17:11:22

您是说要使用Web服务?还是托管网络服务?

Do you mean you want to consume a webservice? Or Host a web service?

如果您要使用Web服务,请按照建议的方式添加WebReference.

If you want to consume a web service, Add WebReference as billb suggested.

如果要托管Web服务,则不能托管ASMX Web服务.但是,可以托管WCF Web服务.

If you want to host a web service, it is not possible to host an ASMX web service. However, it is possible to host a WCF web service.

(示例不包括任何错误处理或您想要的东西.)

(Example Does not include any error handling or things that you would want.)

声明您的合同

[ServiceContract]
public interface  IWebGui
{
    [OperationContract]
    [WebGet(UriTemplate= "/")]
    Stream GetGrid();
}

履行合同

[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)]
public class WebGui : IWebGui
{

    public Stream GetGrid()
    {

        string output = "test";


        MemoryStream ms = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(output));
        WebOperationContext.Current.OutgoingResponse.ContentType = "text/html";
        return ms;
    }

}

然后启动一个WebServiceHost来服务该呼叫

Then start a WebServiceHost to serve the call

        WebGui webGui = new WebGui();

        host = new WebServiceHost(webGui, new Uri("http://localhost:" + Port));
        var bindings = new WebHttpBinding();

        host.AddServiceEndpoint(typeof(IWebGui), bindings, "");
        host.Open();