如何从Windows表单应用程序调用Web API登录操作
如何从Windows表单应用程序调用Web API登录操作
我有一个简单的Web API,其中包含注册、登录和调用API模块。我想从Windows表单应用程序中调用每个功能。\n在Web API中,我使用以下JavaScript脚本调用登录方法:\n
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); // 将访问令牌缓存到会话存储中。 sessionStorage.setItem(tokenKey, data.access_token); }).fail(showError); }
\n我的控制器动作如下:\n
// POST api/Account/AddExternalLogin [Route("AddExternalLogin")] public async TaskAddExternalLogin(AddExternalLoginBindingModel model) { // ... } // POST api/Account/RemoveLogin [Route("RemoveLogin")] public async Task RemoveLogin(RemoveLoginBindingModel model) { // ... } // GET api/Account/ExternalLogin [OverrideAuthentication] [HostAuthentication(DefaultAuthenticationTypes.ExternalCookie)] [AllowAnonymous] [Route("ExternalLogin", Name = "ExternalLogin")] public async Task GetExternalLogin(string provider, string error = null) { // ... } // GET api/Account/ExternalLogins?returnUrl=%2F&generateState=true [AllowAnonymous] [Route("ExternalLogins")] public IEnumerable GetExternalLogins(string returnUrl, bool generateState = false) { // ... }
\n我在WinForm中使用以下代码调用登录动作:\n
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;
\n在上述代码中,我尝试调用控制器动作,但失败了。为了实现我的目标,甚至从WinForm应用程序中调用JavaScript也可以。
问题出现的原因是需要从Windows窗体应用程序中调用Web API登录操作。解决方法是使用HttpWebRequest和HttpWebResponse进行POST和GET请求。
以下是解决方法的代码示例:
// POST请求 var httpWebRequest = (HttpWebRequest)WebRequest.Create("path/api"); httpWebRequest.ContentType = "text/json"; httpWebRequest.Method = WebRequestMethods.Http.Post; httpWebRequest.Accept = "application/json; charset=utf-8"; // 可能需要添加的代码 // httpWebRequest.ContentLength = json.Length; // 发送请求 using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) { // 写入POST数据 // 你也可以使用JavaScriptSerializer将对象序列化 streamWriter.Write(json); streamWriter.Flush(); } // 获取响应 using (var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse()) { // 读取响应 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"; // 获取响应 using (var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse()) { // 读取响应 using (Stream stream = httpResponse.GetResponseStream()) { using (StreamReader re = new StreamReader(stream)) { String jsonResponce = re.ReadToEnd(); } } }
你也可以阅读这个SO回答获取更多信息。
问题的原因是用户想要从Windows表单应用程序中调用Web API登录操作。他们可能遇到了一些困难,需要寻求解决方法。
解决方法可以在以下链接中找到:call web api from c sharp。
问题原因:HttpClient类中没有名为PostAsJsonAsync的定义。
解决方法:使用System.Net.Http.Formatting扩展包,添加对Json的支持。
using System.Net.Http; using System.Net.Http.Formatting; 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); HttpContent content = new ObjectContent(paramList, new JsonMediaTypeFormatter()); HttpResponseMessage response = client.PostAsync("api/product/SupplierAndProduct", content).Result;
以上代码使用ObjectContent和JsonMediaTypeFormatter来将参数列表转换为Json格式,并使用PostAsync方法发送请求。