Append soap header in asp.net web service
Web Service :
using System;
using System.Collections;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
/// <summary>
/// WebService 的摘要描述
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// 若要允許使用 ASP.NET AJAX 從指令碼呼叫此 Web 服務,請取消註解下一行。
// [System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService
{
public WebService()
{
//如果使用設計的元件,請取消註解下行程式碼
//InitializeComponent();
}
public AuthHeader authHeader;
[WebMethod]
[SoapHeader("authHeader")]
public string Concat(string key, string value)
{
if (IsValidToken1())
return string.Format("({0},{1})", key, value);
else
throw new Exception("Not valid token1");
}
private bool IsValidToken1()
{
//if (authHeader.Token1 == "") ;
return true;
}
}
/// <summary>
/// 定義自行加入的header認證
/// </summary>
public class AuthHeader : SoapHeader
{
private string _Token1;
public string Token1
{
get { return _Token1; }
set { _Token1 = value; }
}
}
Web Service client :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication
{
class CallWebService
{
/// <summary>
/// .net framework 2.0
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
/// <returns></returns>
public static string Call20(string key, string value)
{
ConsoleApplication.WSforTest.AuthHeader authHeader = new ConsoleApplication.WSforTest.AuthHeader();
authHeader.Token1 = "TestToken1";
ConsoleApplication.WSforTest.WebServiceForTest wsTest = new ConsoleApplication.WSforTest.WebServiceForTest();
wsTest.AuthHeaderValue = authHeader;
return wsTest.Concat(key, value);
}
/// <summary>
/// .net framework 3.5
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
/// <returns></returns>
public static string Call35(string key, string value)
{
ConsoleApplication.WSforTest35.AuthHeader authHeader = new ConsoleApplication.WSforTest35.AuthHeader();
authHeader.Token1 = "TestToken1";
ConsoleApplication.WSforTest35.WebServiceForTestSoapClient client = new ConsoleApplication.WSforTest35.WebServiceForTestSoapClient();
return client.Concat(authHeader, key, value);
}
}
}