2016-03-04 72 views
2

因此,我需要從c#執行一系列的請求到web api,並且他們需要基本身份驗證。我知道我可以這樣做:爲來自web.config文件的http請求配置身份驗證

var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://url"); 

     String username = "abc"; 
     String password = "123"; 
     String encoded = Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password)); 
     httpWebRequest.Headers.Add("Authorization", "Basic " + encoded); 
     httpWebRequest.ContentType = "application/json"; 
     httpWebRequest.Method = "POST"; 

但我不想手動將憑據添加到每個請求的標頭。我想知道是否有一種方法可以全局驗證我的所有請求(從web.config,可能類似於connectionStrings for sql連接?)。

+0

您可以隨時添加全局過濾器,或者添加i t手動以上任何具體的方法,你需要添加爲 – harishr

回答

0

你可以創建一個繼承HttpClient的一個類,你建議從web.config

public class AuthenticatedClient : HttpClient 
{ 
    public AuthenticatedClient() 
    { 
     string password = ConfigurationManager.AppSettings["Password"]; 
     string userName = ConfigurationManager.AppSettings["UserName"]; 
     string encoded = Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(userName + ":" + password)); 

     BaseAddress = new Uri("http://url"); 
     DefaultRequestHeaders.Add("Authorization", "Basic " + encoded); 
     DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 
    } 
} 

,並在web.config

<appSettings> 
    <add key="UserName" value="abc" /> 
    <add key="Password" value="123" /> 
</appSettings> 

然後獲取用戶名和密碼,無論你想要使用它就像使用標準HttpClient一樣

StringContent stringContent = new StringContent("json request string", UnicodeEncoding.UTF8, "application/json"); 

using (var client = new AuthenticatedClient()) 
{ 
    HttpResponseMessage response = await client.PostAsync("/api/whatever", stringContent); 
} 
+0

不完全是我在找什麼,但一個有趣的解決方案。感謝名單! –

0

如果你想讓你的憑證是靜態的,但可以改變,那麼你可以繼續你的想法,並將用戶名和密碼添加到web.config應用程序設置。請參閱this

您可以創建一個添加授權標頭的實用程序方法。

public static void AddAuthorizationHeader(ref HttpWebRequest request) 
{ 
    string username = //load value from web.config 
    string password = //load value from web.config 
    string encoded = Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password)); 
request.Headers.Add("Authorization", "Basic " + encoded); 
} 

所以只是用它像這樣需要該頭所有的HTTP Web請求..

HttpWebRequest request = new HttpWebRequest(); 
UtilityClass.AddAuthorizationHeader(ref request); 
request.ContentType = "application/json"; 
request.Method = "POST"; 

附:我正在使用我的手機,對於這個可憐的答案感到抱歉。但我想這是你需要的。