傳統 ASMX Web Service 常透過 SOAP Header 傳遞驗證資訊,但非 .NET 客戶端 (Java, PHP, Python) 處理 SOAP Header 較為繁瑣。利用 ASP.NET 內建 Session 機制,配合 [WebMethod(EnableSession = true)],可實現類似網站登入的狀態驗證:先呼叫登入方法建立 Session,後續方法檢查 Session 狀態即可。
using System.Web.Services;
public class ArchiveService : WebService {
///
/// 授權驗證,建立 Session
///
[WebMethod(EnableSession = true, MessageName = "授權驗證")]
public bool CheckAuthorize(string appName, string appAuthorizeCode) {
bool authorized = (appName == "帳號名稱" && appAuthorizeCode == "123456");
Session["Login"] = authorized;
return authorized;
}
///
/// 業務方法,需先通過驗證
///
[WebMethod(EnableSession = true, MessageName = "添加檔案")]
public string AddArchive(Archives model) {
try {
if (Session["Login"] != null && (bool)Session["Login"]) {
var bll = new BLL.Archives();
return bll.AddArchive(model) ? "檔案添加成功" : "檔案添加失敗";
}
return "未通過驗證";
} catch (Exception ex) {
return ex.Message;
}
}
}
CheckAuthorize("帳號名稱", "123456"),取得回傳 true 並自動接收 Set-Cookie: ASP.NET_SessionId=...。AddArchive 讀取 Session["Login"] 判斷權限。CookieContainer) 維持 Session。///
/// 授權驗證,在調用Web Service的時候先調用這個方法,
/// 調用完成後就像普通網站登錄一樣,只要Session不超時就不需要再次調用此方法了
///
[WebMethod(EnableSession = true, MessageName = "授權驗證")]
public bool CheckAuthorize(string appName, string appAuthorizeCode) {
if (appName == "帳號名稱" && appAuthorizeCode == "123456")
Session["Login"] = true;
else
Session["Login"] = false;
return (bool)Session["Login"];
}
///
/// 添加檔案,然後再調用
///
[WebMethod(EnableSession = true, MessageName = "添加檔案")]
public string AddArchive(Model.Archives model) {
try {
if (Session["Login"] != null && Session["Login"].Equals(true)) {
BLL.Archives bll = new BLL.Archives();
if (bll.AddArchive(model))
return "檔案添加成功";
else
return "檔案添加失敗";
} else
return "未通過驗證";
} catch (Exception err) {
return err.Message;
}
}