2013-05-09 20 views
1

請給我一個示例代碼來設置Web API服務的HTTP頭。如何通過http頭使用基本認證從ipad應用程序調用web api服務?

我開發的基本認證。

public class BasicAuthenticationFilter : AuthorizationFilterAttribute 
    { 
     bool Active = true; 

     public BasicAuthenticationFilter() 
     { } 

     /// <summary> 
     /// Overriden constructor to allow explicit disabling of this 
     /// filter's behavior. Pass false to disable (same as no filter 
     /// but declarative) 
     /// </summary> 
     /// <param name="active"></param> 
     public BasicAuthenticationFilter(bool active) 
     { 
      Active = active; 
     } 


     /// <summary> 
     /// Override to Web API filter method to handle Basic Auth check 
     /// </summary> 
     /// <param name="actionContext"></param> 
     public override void OnAuthorization(HttpActionContext actionContext) 
     { 
      if (Active) 
      { 
       var identity = ParseAuthorizationHeader(actionContext); 
       if (identity == null) 
       { 
        //Challenge(actionContext); 
        actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized); 
        return; 
       } 


       if (!OnAuthorizeUser(identity.Name, identity.Password, actionContext)) 
       { 
        Challenge(actionContext); 
        return; 
       } 

       var principal = new GenericPrincipal(identity, null); 

       Thread.CurrentPrincipal = principal; 

       // inside of ASP.NET this is required 
       //if (HttpContext.Current != null) 
       // HttpContext.Current.User = principal; 

       base.OnAuthorization(actionContext); 
      } 
     } 

     /// <summary> 
     /// Base implementation for user authentication - you probably will 
     /// want to override this method for application specific logic. 
     /// 
     /// The base implementation merely checks for username and password 
     /// present and set the Thread principal. 
     /// 
     /// Override this method if you want to customize Authentication 
     /// and store user data as needed in a Thread Principle or other 
     /// Request specific storage. 
     /// </summary> 
     /// <param name="username"></param> 
     /// <param name="password"></param> 
     /// <param name="actionContext"></param> 
     /// <returns></returns> 
     protected virtual bool OnAuthorizeUser(string username, string password, HttpActionContext actionContext) 
     { 
      if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password)) 
       return false; 

      return true; 
     } 

     /// <summary> 
     /// Parses the Authorization header and creates user credentials 
     /// </summary> 
     /// <param name="actionContext"></param> 
     protected virtual BasicAuthenticationIdentity ParseAuthorizationHeader(HttpActionContext actionContext) 
     { 
      string authHeader = null; 
      var auth = actionContext.Request.Headers.Authorization; 
      if (auth != null && auth.Scheme == "Basic") 
       authHeader = auth.Parameter; 

      if (string.IsNullOrEmpty(authHeader)) 
       return null; 

      authHeader = Encoding.Default.GetString(Convert.FromBase64String(authHeader)); 

      var tokens = authHeader.Split(':'); 
      if (tokens.Length < 2) 
       return null; 

      return new BasicAuthenticationIdentity(tokens[0], tokens[1]); 
     } 


     /// <summary> 
     /// Send the Authentication Challenge request 
     /// </summary> 
     /// <param name="message"></param> 
     /// <param name="actionContext"></param> 
     void Challenge(HttpActionContext actionContext) 
     { 
      var host = actionContext.Request.RequestUri.DnsSafeHost; 
      actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized); 
      actionContext.Response.Headers.Add("WWW-Authenticate", string.Format("Basic realm=\"{0}\"", host)); 
     } 
    } 
    public class BasicAuthenticationIdentity : GenericIdentity 
    { 
     public BasicAuthenticationIdentity(string name, string password) 
      : base(name, "Basic") 
     { 
      this.Password = password; 
     } 

     /// <summary> 
     /// Basic Auth Password for custom authentication 
     /// </summary> 
     public string Password { get; set; } 
    } 
    public class BasicAuthCredentials 
    { 
     public string Username { get; set; } 
     public string Password { get; set; } 
    } 

[BasicAuthenticationFilter] 
public class SampleController : ApiController 
    { 

     public string Get() 
     { 
      return "Hai Authentication successfully done!"; 
     } 

    } 

所以我需要從基於http頭(目標c)的ipad應用程序調用web api服務。

高級謝謝。

+0

感謝您的回覆。我們如何設置http頭來調用服務。像(內容類型,接受等)。謝謝。 – user2285357 2013-05-09 10:01:58

回答

1

我認爲這可以幫助你很好地理解它。

NSString *soapMessage=[NSString stringWithFormat:@"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" 
          "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n" 
          "<soap:Body>\n" 
          "</soap:Body>\n" 
          "</soap:Envelope>\n", URL_Temp,]; 



    NSURL *tmpURl=[NSURL URLWithString:[NSString stringWithFormat:@"%s/%s", URL_Main, URL_Service]]; 

    NSMutableURLRequest *theRequest=[NSMutableURLRequest requestWithURL:tmpURl]; 
    [theRequest addValue:@"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"]; 

    NSString *msgLength=[NSString stringWithFormat:@"%i",[soapMessage length]]; 
    [theRequest addValue:msgLength forHTTPHeaderField:@"Content-Length"]; 
    [theRequest setHTTPMethod:@"POST"]; 

    [theRequest setHTTPBody:[soapMessage dataUsingEncoding:NSUTF8StringEncoding]]; 
    con=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self]; 
    if(con) 
    { 
     webdata=[[NSMutableData data] retain]; 
    } 
+0

請看更新的回答 – Impossible 2013-05-09 10:07:31

+0

非常感謝你 – user2285357 2013-05-09 10:18:49

相關問題