亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

ASP.NET實現(xiàn)基于Forms認證的WebService應用實例

 更新時間:2015年05月08日 15:26:22   作者:xujh  
這篇文章主要介紹了ASP.NET實現(xiàn)基于Forms認證的WebService應用,實例分析了使用Forms進行WebService身份認證的相關技巧與實現(xiàn)方法,需要的朋友可以參考下

本文實例講述了ASP.NET實現(xiàn)基于Forms認證的WebService應用方法。分享給大家供大家參考。具體實現(xiàn)方法如下:

在安全性要求不是很高的ASP.Net程序中,基于Forms的身份驗證是經(jīng)常使用的一種方式,而如果需要對WebService進行身份驗證,最常用的可能是基于Soap 標頭的自定義身份驗證方式。如果對兩者做一下比較的話,顯然,基于Forms的驗證方式更加方便易用,能否將Forms驗證方式應用到WebService中去呢?

從理論上講,使用基于Forms的方式對WebService進行身份驗證是可行的,但是使用過程中會存在以下兩個問題:

1.基于Forms的驗證方式同時也是基于Cookie的驗證方式,在使用瀏覽器時,這個問題是不需要我們考慮的。但對于使用WebService的應用程序來說,默認是不能保存Cookie的,需要我們自己去做這個工作。

2.WebService既然是一個A2A(Application To Application)應用程序,使用Web表單進行身份驗證顯然不太合適,而且,這將不可避免的造成人機交互,使WebService的應用大打折扣。

接下來,我們就分步解決這兩個問題:

1.Cookie的保存問題

WebService的客戶端代理類有一個屬性CookieContainer可用于設置或獲取Cookie集合,保存Cookie的任務就交給他了:

System.Net.CookieContainer cookieContainer = new System.Net.CookieContainer();
MyService.WebService service = new App.MyService.WebService();
service.CookieContainer = cookieContainer;

2.我們不想使用Web表單進行身份驗證,幸運的是,ASP.Net表單驗證中的表單頁(即Web.config文件中 forms 元素內(nèi)的loginUrl)同樣可以指定為WebService文件。
我們創(chuàng)建一個專門用作身份驗證的Web服務,暫且命名為Login.asmx,然后讓 loginUrl 等于 “Login.asmx”,當然,還需要在Web.config文件中的 authorization 節(jié)中禁止匿名訪問(否則我們可就白忙活了),完成配置后的Web.config文件如下:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
 <system.web>
 <compilation debug="false" />
 <authentication mode="Forms">
 <forms name="MyService" loginUrl="Login.asmx"></forms>
 </authentication>
 <authorization >
 <deny users="?"/>
 </authorization>
 </system.web>
</configuration>

其實我們并不想在未通過身份驗證時讓瀏覽器轉(zhuǎn)向到Login.asmx,對于使用WebService的客戶程序來說,真正的實惠在于:可以匿名訪問Login.asmx中的方法(當然我們也可以把Login.asmx放在單獨的目錄中,然后允許對該目錄的匿名訪問來達個這個目的,但我覺得還是用loginUrl更優(yōu)雅一些)。

接下來,我們?yōu)長ogin.asmx添加用于身份驗證的WebMethod:

[WebMethod]
public bool Check(string userName,string password)
{
 if(userName == "aaaaaa" && password == "123456")
 //添加驗證邏輯
 {
 System.Web.Security.FormsAuthentication.SetAuthCookie(userName, false);
 return true;
 }
 else
 {
 return false;
 }
}

最后一步工作就是:讓客戶程序中的WebService實例與Login實例共享CookieContainer。

class Sample
{
 System.Net.CookieContainer cookieContainer = new System.Net.CookieContainer();
 public void Login()
 {
 MyServiceLogin.Login login = new App.MyServiceLogin.Login();
 login.CookieContainer = cookieContainer;
 login.Check("aaaaaa", "123456");   
 }
 public void ShowHelloWorld()
 {
 MyService.WebService service = new App.MyService.WebService();
 service.CookieContainer = cookieContainer;
 Console.WriteLine(service.HelloWorld());
 }
}

Login()以后再ShowHelloWorld(),你是否看到了我們熟悉的“Hello World”?Ok,就這么簡單!

希望本文所述對大家的C#程序設計有所幫助。

相關文章

最新評論