(转)WebService head加密,可以对 WebService设置访问用户名和密码,增强 WebService的安全性 使 WebService只能被授权用户使用。
具体实现步骤:
1、 定义一个 soapheader派生类用来实现 WebService访问权限验证
- <span style="font-size:10px;">using System;
- using System.Data;
- using System.Configuration;
- using System.Web;
- using System.Web.Security;
- using System.Web.UI;
- using System.Web.UI.HtmlControls;
- using System.Web.UI.WebControls;
- using System.Web.UI.WebControls.WebParts;
-
- public class MySoapHeader:System .Web .Services .Protocols .SoapHeader
- {
- private string _uname = string.Empty;
-
- public string Uname
- {
- get { return _uname; }
- set { _uname = value; }
- }
- private string _password = string.Empty;
-
- public string Password
- {
- get { return _password; }
- set { _password = value; }
- }
-
-
- public MySoapHeader()
- {
-
-
-
- }
- public MySoapHeader(string uname, string upass)
- {
- init(uname, upass);
- }
- private void init(string uname, string upass)
- {
- this._password = upass;
- this._uname = uname;
- }
-
- private bool isValid(string uname, string upass, out string msg)
- {
- msg = "";
- if (uname == "admin" && upass =="admin")
- {
- return true;
- }
- else {
- msg = "对不起!您无权调用此WebService!";
- return false;
- }
- }
-
- public bool isValid(out string msg)
- {
- return isValid(_uname, _password,out msg);
- }
- }
-
-
- </span>
2、 定义有需要验证的 WebService。
- <span style="font-size:10px;">using System;
- using System.Collections;
- using System.Linq;
- using System.Web;
- using System.Web.Services;
- using System.Web.Services.Protocols;
- using System.Xml.Linq;
-
- [WebService(Namespace = "http://tempuri.org/")]
- [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
- public class test : System.Web.Services.WebService {
-
- public test () {
-
-
-
- }
- public MySoapHeader myheader = new MySoapHeader();
- [WebMethod]
- public string HelloWorld() {
- return "Hello World";
- }
- [SoapHeader("myheader")]
-
- [WebMethod(Description = "根据产品编号查询产品的价格", EnableSession = true)]
-
- public string GetProductPrice2(string ProductId)
- {
-
- string msg = "";
-
-
-
- if (!myheader.isValid(out msg))
- {
-
- return -1;
-
- }
-
- return ProductId;
- }
- }
- </span>
3、 客户端调用方法
引用 WebService定义 WebService名称为 :Myservice
- <span style="font-size:10px;">using System;
- using System.Configuration;
- using System.Data;
- using System.Web;
- using System.Web.Security;
- using System.Web.UI;
- using System.Web.UI.HtmlControls;
- using System.Web.UI.WebControls;
- using System.Web.UI.WebControls.WebParts;
- public partial class _Default : System.Web.UI.Page
- {
- protected void Page_Load(object sender, EventArgs e)
- {
- myservice.test te = new abc.test();
- myservice.MySoapHeader myhead = new MySoapHeader();
- myhead.Uname = "admin";
- myhead.Password = "admin";
- te.MySoapHeaderValue = myhead;
- string test = te.GetProductPrice2("ok!");
- Response.Write(aa);
- }
webService访问加密-Soapheader,布布扣,bubuko.com
webService访问加密-Soapheader
原文:http://www.cnblogs.com/aresyl/p/3837938.html