2016-07-01 31 views
4

我有一個簡單的Web API,具有註冊,登錄和調用API模塊。我想從Windows窗體應用程序調用每個功能。如何從Windows窗體應用程序調用Web API登錄操作

在網絡API,我用下面的腳本中的JavaScript調用登錄方法:

self.login = function() { 
    self.result(''); 

    var loginData = { 
     grant_type: 'password', 
     username: self.loginEmail(), 
     password: self.loginPassword() 
    }; 

    $.ajax({ 
     type: 'POST', 
     url: '/Token', 
     data: loginData 
    }).done(function (data) { 
     self.user(data.userName); 
     // Cache the access token in session storage. 
     sessionStorage.setItem(tokenKey, data.access_token); 
    }).fail(showError); 
} 

我的控制器操作如下

// POST api/Account/AddExternalLogin 
    [Route("AddExternalLogin")] 
    public async Task<IHttpActionResult> AddExternalLogin(AddExternalLoginBindingModel model) 
    { 
     if (!ModelState.IsValid) 
     { 
      return BadRequest(ModelState); 
     } 

     Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie); 

     AuthenticationTicket ticket = AccessTokenFormat.Unprotect(model.ExternalAccessToken); 

     if (ticket == null || ticket.Identity == null || (ticket.Properties != null 
      && ticket.Properties.ExpiresUtc.HasValue 
      && ticket.Properties.ExpiresUtc.Value < DateTimeOffset.UtcNow)) 
     { 
      return BadRequest("External login failure."); 
     } 

     ExternalLoginData externalData = ExternalLoginData.FromIdentity(ticket.Identity); 

     if (externalData == null) 
     { 
      return BadRequest("The external login is already associated with an account."); 
     } 

     IdentityResult result = await UserManager.AddLoginAsync(User.Identity.GetUserId(), 
      new UserLoginInfo(externalData.LoginProvider, externalData.ProviderKey)); 

     if (!result.Succeeded) 
     { 
      return GetErrorResult(result); 
     } 

     return Ok(); 
    } 

    // POST api/Account/RemoveLogin 
    [Route("RemoveLogin")] 
    public async Task<IHttpActionResult> RemoveLogin(RemoveLoginBindingModel model) 
    { 
     if (!ModelState.IsValid) 
     { 
      return BadRequest(ModelState); 
     } 

     IdentityResult result; 

     if (model.LoginProvider == LocalLoginProvider) 
     { 
      result = await UserManager.RemovePasswordAsync(User.Identity.GetUserId()); 
     } 
     else 
     { 
      result = await UserManager.RemoveLoginAsync(User.Identity.GetUserId(), 
       new UserLoginInfo(model.LoginProvider, model.ProviderKey)); 
     } 

     if (!result.Succeeded) 
     { 
      return GetErrorResult(result); 
     } 

     return Ok(); 
    } 

    // GET api/Account/ExternalLogin 
    [OverrideAuthentication] 
    [HostAuthentication(DefaultAuthenticationTypes.ExternalCookie)] 
    [AllowAnonymous] 
    [Route("ExternalLogin", Name = "ExternalLogin")] 
    public async Task<IHttpActionResult> GetExternalLogin(string provider, string error = null) 
    { 
     if (error != null) 
     { 
      return Redirect(Url.Content("~/") + "#error=" + Uri.EscapeDataString(error)); 
     } 

     if (!User.Identity.IsAuthenticated) 
     { 
      return new ChallengeResult(provider, this); 
     } 

     ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(User.Identity as ClaimsIdentity); 

     if (externalLogin == null) 
     { 
      return InternalServerError(); 
     } 

     if (externalLogin.LoginProvider != provider) 
     { 
      Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie); 
      return new ChallengeResult(provider, this); 
     } 

     ApplicationUser user = await UserManager.FindAsync(new UserLoginInfo(externalLogin.LoginProvider, 
      externalLogin.ProviderKey)); 

     bool hasRegistered = user != null; 

     if (hasRegistered) 
     { 
      Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie); 

      ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(UserManager, 
       OAuthDefaults.AuthenticationType); 
      ClaimsIdentity cookieIdentity = await user.GenerateUserIdentityAsync(UserManager, 
       CookieAuthenticationDefaults.AuthenticationType); 

      AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user.UserName); 
      Authentication.SignIn(properties, oAuthIdentity, cookieIdentity); 
     } 
     else 
     { 
      IEnumerable<Claim> claims = externalLogin.GetClaims(); 
      ClaimsIdentity identity = new ClaimsIdentity(claims, OAuthDefaults.AuthenticationType); 
      Authentication.SignIn(identity); 
     } 

     return Ok(); 
    } 

    // GET api/Account/ExternalLogins?returnUrl=%2F&generateState=true 
    [AllowAnonymous] 
    [Route("ExternalLogins")] 
    public IEnumerable<ExternalLoginViewModel> GetExternalLogins(string returnUrl, bool generateState = false) 
    { 
     IEnumerable<AuthenticationDescription> descriptions = Authentication.GetExternalAuthenticationTypes(); 
     List<ExternalLoginViewModel> logins = new List<ExternalLoginViewModel>(); 

     string state; 

     if (generateState) 
     { 
      const int strengthInBits = 256; 
      state = RandomOAuthStateGenerator.Generate(strengthInBits); 
     } 
     else 
     { 
      state = null; 
     } 

     foreach (AuthenticationDescription description in descriptions) 
     { 
      ExternalLoginViewModel login = new ExternalLoginViewModel 
      { 
       Name = description.Caption, 
       Url = Url.Route("ExternalLogin", new 
       { 
        provider = description.AuthenticationType, 
        response_type = "token", 
        client_id = Startup.PublicClientId, 
        redirect_uri = new Uri(Request.RequestUri, returnUrl).AbsoluteUri, 
        state = state 
       }), 
       State = state 
      }; 
      logins.Add(login); 
     } 

     return logins; 
    } 

我使用下面的代碼在winform調用登錄動作:

HttpClient client = new HttpClient(); 

     Uri baseAddress = new Uri("https://localhost:44305/"); 

     client.BaseAddress = baseAddress; 

     ArrayList paramList = new ArrayList(); 
     user u = new user(); 
     u.username = username; 
     u.password = password; 

     paramList.Add(u); 


     HttpResponseMessage response = client.PostAsJsonAsync("api/product/SupplierAndProduct", paramList).Result; 

在上面的代碼中,我嘗試調用控制器操作,但是fai LED。爲了實現我的目標,即使從winform應用程序調用JavaScript也沒問題。

回答

3
HttpClient client = new HttpClient(); 
Uri baseAddress = new Uri("http://localhost:2939/"); 
client.BaseAddress = baseAddress; 

ArrayList paramList = new ArrayList(); 
Product product = new Product { ProductId = 1, Name = "Book", Price = 500, Category = "Soap" }; 
Supplier supplier = new Supplier { SupplierId = 1, Name = "AK Singh",  Address = "Delhi" }; 
paramList.Add(product); 
paramList.Add(supplier); 

HttpResponseMessage response = client.PostAsJsonAsync("api/product/SupplierAndProduct", paramList).Result; 
+0

發生一個錯誤,告訴httpclint不包含定義PostAsJsonAsync –

+0

告訴我你的代碼 –

+0

代碼更新 – rakshi

2

我通常使用HttpWebRequestHttpWebResponce的情況下,像你這樣的:

//POST 
var httpWebRequest = (HttpWebRequest)WebRequest.Create("path/api"); 
httpWebRequest.ContentType = "text/json"; 
httpWebRequest.Method = WebRequestMethods.Http.Post; 
httpWebRequest.Accept = "application/json; charset=utf-8"; 
//probably have to be added 
//httpWebRequest.ContentLength = json.Length; 

//do request 
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) 
{ 
    //write post data 
    //also you can serialize yours objects by JavaScriptSerializer 
    streamWriter.Write(json); 
    streamWriter.Flush(); 
} 

//get responce 
using (var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse()) 
{ 
    //read 
    using (Stream stream = httpResponse.GetResponseStream()) 
    { 
     using (StreamReader re = new StreamReader(stream)) 
     { 
      String jsonResponce = re.ReadToEnd(); 
     } 
    } 
} 

//GET 
var httpWebRequest = (HttpWebRequest)WebRequest.Create("path/api"); 
httpWebRequest.ContentType = "text/json"; 
httpWebRequest.Method = WebRequestMethods.Http.Get; 
httpWebRequest.Accept = "application/json; charset=utf-8"; 

//get responce 
using (var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse()) 
{ 
    //read 
    using (Stream stream = httpResponse.GetResponseStream()) 
    { 
     using (StreamReader re = new StreamReader(stream)) 
     { 
      String jsonResponce = re.ReadToEnd(); 
     } 
    } 
} 

你也前人的精力閱讀本SO answer

0
 //GET 
     var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://160.114.10.17:85/api/Inventory/GetProcessDataByProcessName?deviceCode=OvCHY1ySowF4T2bb8HdcYA==&processName=Main Plant"); 
     httpWebRequest.ContentType = "text/json"; 
     httpWebRequest.Method = WebRequestMethods.Http.Get; 
     httpWebRequest.Accept = "application/json; charset=utf-8"; 

     //get responce 
     using (var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse()) 
     { 
      //read 
      using (Stream stream = httpResponse.GetResponseStream()) 
      { 
       using (StreamReader re = new StreamReader(stream)) 
       { 
        String jsonResponce = re.ReadToEnd(); 
       } 
      } 
     } 
+0

我曾嘗試這個代碼,現在它的工作 –

+0

看起來就像在你的代碼中沒有指定控制器名和方法名的API網址。請檢查我的API網址 –

相關問題