2014-01-13 99 views
0

在我的應用中,用戶需要通過服務器進行身份驗證才能使用WebAPI下載數據。 MvvmCross DownloadCache插件似乎只處理基本的HTTP GET查詢。我無法將我的身份驗證令牌添加到網址中,因爲它是一個很大的SAML令牌。帶驗證的MvvmCross HTTP DownloadCache

如何將HTTP標頭添加到通過DownloadCache插件完成的查詢中?

隨着目前的版本,我認爲我應該注入我自己的IMvxHttpFileDownloader,但我正在尋找一個更簡單的解決方案。注入我自己的MvxFileDownloadRequest會更好(不完美),但它沒有接口...

回答

1

我能夠爲自定義方案(http-auth://)註冊一個自定義IWebRequestCreate。

從我的數據源中轉換urls有點難看,但它完成了這項工作。

public class AuthenticationWebRequestCreate : IWebRequestCreate 
    { 
    public const string HttpPrefix = "http-auth"; 
    public const string HttpsPrefix = "https-auth"; 

    private static string EncodeCredential(string userName, string password) 
    { 
     Encoding encoding = Encoding.GetEncoding("iso-8859-1"); 
     string credential = userName + ":" + password; 
     return Convert.ToBase64String(encoding.GetBytes(credential)); 
    } 

    public static void RegisterBasicAuthentication(string userName, string password) 
    { 
     var authenticateValue = "Basic " + EncodeCredential(userName, password); 
     AuthenticationWebRequestCreate requestCreate = new AuthenticationWebRequestCreate(authenticateValue); 
     Register(requestCreate); 
    } 

    public static void RegisterSamlAuthentication(string token) 
    { 
     var authenticateValue = "SAML2 " + token; 
     AuthenticationWebRequestCreate requestCreate = new AuthenticationWebRequestCreate(authenticateValue); 
     Register(requestCreate); 
    } 

    private static void Register(AuthenticationWebRequestCreate authenticationWebRequestCreate) 
    { 
     WebRequest.RegisterPrefix(HttpPrefix, authenticationWebRequestCreate); 
     WebRequest.RegisterPrefix(HttpsPrefix, authenticationWebRequestCreate); 
    } 

    private readonly string _authenticateValue; 

    public AuthenticationWebRequestCreate(string authenticateValue) 
    { 
     _authenticateValue = authenticateValue; 
    } 

    public WebRequest Create(System.Uri uri) 
    { 
     UriBuilder uriBuilder = new UriBuilder(uri); 
     switch (uriBuilder.Scheme) 
     { 
     case HttpPrefix: 
      uriBuilder.Scheme = "http"; 
      break; 
     case HttpsPrefix: 
      uriBuilder.Scheme = "https"; 
      break; 
     default: 
      break; 
     } 
     HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uriBuilder.Uri); 
     request.Headers[HttpRequestHeader.Authorization] = _authenticateValue; 
     return request; 
    } 
    }