C#/.NET WebService的一步步創建使用及訪問驗證
廢話就不多說了,直接開始建工程
1、首先創建MVC項目
2、在工程目錄下創建Remote文件夾(使用規範)
3、文件夾中添加【Web服務(asmx)】新建項
4、在axmx文件中寫接口代碼—Web方法要有WebMethod標記
[WebMethod]//必須標記
public string HelloWorld()
{
return "Hello World";
}
[WebMethod]//必須標記
public int Plus(int x, int y)
{
return x + y;
}
//沒擴展的是無法找到的
public int Minus(int x, int y)
{
return x - y;
}
5、新建Uinit單元測試項目
6、添加服務引用:右鍵打開【Web服務(asmx)】文件在瀏覽器中運行,然後複製Url,再粘貼至服務引用中
先打開【Web服務(asmx)】文件
添加服務引用
7、最後using(xxx.xxClient client = new xxx.xxClient()),後面就是正常用了。
[TestMethod]//測試方法
public void TestMethod()
{
using (WebServiceTest.WebServiceSoapClient client = new WebServiceTest.WebServiceSoapClient())
{
var result1 = client.HelloWorld();
var result2 = client.Plus(123, 345);
}
}
擴展:
要傳回List數據:
在已經添加的服務引用右鍵->配置服務引用->集合類型選擇Generic.List
添加訪問驗證:
在上面Remote文件夾下建CustomSoapHeader類
/// <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("s") && this.PassWord.Contains("1");
}
}
Web代碼:
[WebMethod]
[System.Web.Services.Protocols.SoapHeader("CustomSoapHeader")]
public List<WebServiceUser> Get()
{
if (this.CustomSoapHeader != null && this.CustomSoapHeader.Validate())
{
return new List<WebServiceUser>()
{
new WebServiceUser()
{
Id=123,
Age=23,
Sex=0,
Name="MrSorry",
Description="高級班的學員1"
},
new WebServiceUser()
{
Id=234,
Age=34,
Sex=0,
Name="專注",
Description="高級班的學員2"
},
};
}
else
{
throw new SoapException("身份驗證不通過", SoapHeaderException.ServerFaultCode);
}
}
public class WebServiceUser
{
public int Id { get; set; }
public int Age { get; set; }
public int Sex { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
訪問代碼:
[TestMethod]//測試方法
public void TestMethod()
{
using (WebServiceTest.WebServiceSoapClient client = new WebServiceTest.WebServiceSoapClient())
{
var result3 = client.Get(new WebServiceTest.CustomSoapHeader()
{
UserName = "s400",
PassWord = "1232433"
});
}
}