(精华)2020年11月3日 WebService WebService的基本使用

127 阅读2分钟

WebService:寄宿在IIS,也就是必须在网站项目

Http协议 SOAP协议

1 Http传输信道,A服务器到B服务器,数据是什么格式传递的
2 XML的数据格式—Http传输解析得到的有用数据
3 SOAP协议—封装格式:在分布式的环境中,描述了如何做数据交换的一个轻量级协议
4 WSDL:属于webservice的标配,标准化描述服务,方便调用
5 UDDI:根据描述查找服务的机制
服务端调用WebService添加服务引用,基于svcUtil.exe生成的
基于wsdl生成的一个代理:屏蔽服务调用的复杂性
单元测试:测试方法—回归测试
WebService安全认证:
Form认证 windows认证
服务方法里面添加账号密码参数
SoapHeader验证

下面来说说WebService的使用:

一:在asp.net网站的路由中配置如下代码

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.IgnoreRoute("Remote/{*pathInfo}");//忽略以Remote开头

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}

二:服务端

/// <summary>
/// MyWebService 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行。 
//[System.Web.Script.Services.ScriptService]
//如果需要服务对外开放 必须标记  [WebMethod]
//数据库格式:XMl
//方法不能重名;
//WebService 5大要素:
//
public class MyWebService : System.Web.Services.WebService
{

    public CustomSoapHeader CustomSoapHeaderPop { get; set; }

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

    [WebMethod]
    [SoapHeader("CustomSoapHeaderPop")]
    public string Get()
    {
        if (!CustomSoapHeaderPop.Validate())
        {
            throw new SoapException("认证失败",SoapException.ClientFaultCode);
        }

        return "认证成功";
    }
    [WebMethod] //如果需要服务对外开放 必须标记  [WebMethod]
    [SoapHeader("CustomSoapHeaderPop")]
    public string GetInfo()
    {
        if (!CustomSoapHeaderPop.Validate())
        {
            throw new SoapException("认证失败", SoapException.ClientFaultCode);
        }
        return Newtonsoft.Json.JsonConvert.SerializeObject(new
        {
            Id = 123,
            Name = "棒棒糖"
        });
    }

    [WebMethod]
    [SoapHeader("CustomSoapHeaderPop")]
    public string GetStudent(int i, string y)
    {
        if (!CustomSoapHeaderPop.Validate())
        {
            throw new SoapException("认证失败", SoapException.ClientFaultCode);
        }
        return Newtonsoft.Json.JsonConvert.SerializeObject(new
        {
            i = i,
            y = y
        });
    }

    [WebMethod]
    public UserInfo GetUserInfo(string name,string password)
    {
        //if (name.Equals("Richard")&&password.Equals("123456"))
        //{

        //}


        return new UserInfo()
        {
            Id = 234,
            Name = "xut"
        };
    }

    [WebMethod]
    public List<UserInfo> GetInfoList(int i, string y)
    {
        return new List<UserInfo>() {
        new UserInfo()
        {
            Id = 345,
            Name = "阳光下的微笑"
        },
          new UserInfo()
        {
            Id = 345,
            Name = "深海无息"
        } 
    };
    }
}
/// <summary>
/// Header:分配个加密钥  账号密码加密
/// 
/// </summary>
public class CustomSoapHeader : System.Web.Services.Protocols.SoapHeader
{

    private string userName = string.Empty;
    private string passWord = string.Empty;
    public CustomSoapHeader()//必须有一个无参数的构造函数
    { }

    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="userName">用户名</param>
    /// <param name="passWord">密码</param>
    public CustomSoapHeader(string userName, string passWord)
    {
        this.userName = userName;
        this.passWord = passWord;
    }
     
    /// <summary>
    /// 获取或设置用户用户名
    /// </summary>
    public string UserName
    {
        get { return userName; }
        set { this.userName = value; }
    }

    /// <summary>
    /// 获取或设置用户密码
    /// </summary>
    public string PassWord
    {
        get { return passWord; }
        set { this.passWord = value; }
    }
    public bool Validate()
    { 
        return this.UserName.Contains("Richard") && this.PassWord.Contains("123456");
    }

}
public class UserInfo
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
}

三:引用端

[TestClass]
public class UnitTest1
{
    [TestMethod]
    public void TestMethod1()
    {
        //using 有什么作用?
        using (MyWebServiceTest.MyWebServiceSoapClient client = new MyWebServiceTest.MyWebServiceSoapClient())
        {
            MyWebServiceTest.CustomSoapHeader heade = new MyWebServiceTest.CustomSoapHeader();
            heade.UserName = "xut";
            heade.PassWord = "123456";
            string str = client.Get(heade);
            string info = client.GetInfo(heade);
            string studnet = client.GetStudent(heade, 123, "xut");
            str = client.GetAsync(heade).Result.GetResult;
            var userInfoList = client.GetInfoList(123, "xut");
        }
    }
}