Fork me on GitHub

WebService 简单应用


Web服务全称:XML Web Service,是一种可编程的应用程序逻辑组件,它可以在Internet或企业网的Web应用程序之间共享。Web服务被设计成能够通过Internet与其它应用程序之间直接交互,因此它没有界面,而是提供了一种称为协定的标准定义接口,该接口描述了XML Web Service 提供的服务。

1、搭建一个Web服务,选择.Net FrameWork3.5

  

选择:ASP.NET Web 服务应用程序。

搭建完毕:我们会看到,Service1.asmx文件,双击打开Service1.asmx.cs文件:

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

namespace WebService1
{
    /// <summary>
    /// Service1 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。
    // [System.Web.Script.Services.ScriptService]
    public class Service1 : System.Web.Services.WebService
    {

        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }
    }
}

 我们可以自定义:

      [WebMethod]
        public int AddNum(int num1, int num2)
        {
            return num1 + num2;
        }

 2、之后我们可以在另一个站点调用:

  (1)新建一个项目Test

  (2)右键引用--添加服务引用,点击发现按钮,地址:出现我们搭建的web服务

    

配置文件中也自动出现:

<system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="Service1Soap" closeTimeout="00:01:00" openTimeout="00:01:00"
          receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false"
          bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
          maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
          messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
          useDefaultWebProxy="true">
          <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
            maxBytesPerRead="4096" maxNameTableCharCount="16384" />
          <security mode="None">
            <transport clientCredentialType="None" proxyCredentialType="None"
              realm="" />
            <message clientCredentialType="UserName" algorithmSuite="Default" />
          </security>
        </binding>
      </basicHttpBinding>
    </bindings>
    <client>
    //如果不是本地的,修改域名,重新在这里配置即可调用 <endpoint address="http://localhost:9041/Service1.asmx" binding="basicHttpBinding" bindingConfiguration="Service1Soap" contract="ServiceReference1.Service1Soap" name="Service1Soap" /> </client> </system.serviceModel> </configuration>

3、此时我们即可在项目中调用:

 

  ServiceReference1.Service1SoapClient myService = new Service1SoapClient();
  ViewData["num"] = myService.AddNum(8, 6);
  return View();

视图中:就会返回两个数的和。

posted @ 2013-09-11 15:04  迁梦余光  阅读(306)  评论(0编辑  收藏  举报