WebService 要来就是公平来的,如果有些方法不需要被别人使用,只允许通过特定许可的人使用,便可以用到 SoapHeader 验证。在 IssueVision 项目中就有用到。现在把一些东西记下来。
首先,新建一个项目(WinForm或Asp.net),我建的叫Win5,再在解决方案中加入一个 WebService,假设名字叫 Service。
在 WebService 中进行如下操作
1.加入一个自定义的 SoapHeader类,MySoapHeader。如下:
”文件“---》“新建网站”---“asp.net web 服务”
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class Service : System.Web.Services.WebService
{
private MySoapHeader m_myheader;
public MySoapHeader MyHeader
{
get
{
return m_myheader;
}
set
{
m_myheader = value;
}
}
public Service () {
//如果使用设计的组件,请取消注释以下行
//InitializeComponent();
}
[WebMethod]
public string HelloWorld() {
return "Hello World";
}
[SoapHeader("MyHeader")]
[WebMethod(Description = "Plus Two Int")]
public int Plus(int a, int b)
{
HeaderCheck.check(this);
return a + b;
}
/// <summary>
/// MySoapHeader 的摘要说明
/// </summary>
public class MySoapHeader : SoapHeader
{
private string m_username;
private string m_password;
public string Username
{
get
{
return m_username;
}
set
{
m_username = value;
}
}
public string Password
{
get
{
return m_password;
}
set
{
m_password = value;
}
}
public MySoapHeader()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
}
/// <summary>
/// HeaderCheck 的摘要说明
/// </summary>
public class HeaderCheck
{
public static void check(Service srv)
{
if (!(srv.MyHeader.Username == "admin" && srv.MyHeader.Password == "admin"))
{
throw new SoapException("Audit Fail", SoapException.ClientFaultCode, "Security");
}
}
public HeaderCheck()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
}
}
然后运行 会看到http://localhost:6742/webservicetest/Service.asmx
然后 建立 客户端
”文件“---》“新建项目”---“windows应用程序”
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace Win5
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Win5.localhost.Service ws = new Win5.localhost.Service();
Win5.localhost.MySoapHeader header = new Win5.localhost.MySoapHeader();
header.Username = "admin";
header.Password = "admin";
ws.MySoapHeaderValue = header; //多了一个"value"
int r = ws.Plus(1,2);
MessageBox.Show(r.ToString());
}
}
}