如何发送认证头在ASP.Net了一套Web请求 [英] How to send authentication header in ASP.Net for set of web request
问题描述
我开发ASP.net应用程序,它消耗的REST服务与ASP.Net的Web API。我试图使用基本身份验证为我的网站。我打算与SSL使用它,一旦我完成基本身份验证。
I am developing ASP.net application which consumes REST services with ASP.Net Web API. I am trying to use Basic authentication for my website. I plan to use it with SSL once I complete Basic authentication.
目前的登录按钮,单击我送使用的用户名和密码的Base64编码验证头,如下所示:
Currently on Login button click I am sending Auth header using Base64 encoding of username and password as shown below:
string responseData = string.Empty;
string authToken = string.Empty;
string loginInstance = url;
// Create request.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(loginInstance);
request.Method = "POST";
request.ContentType = "application/json";
request.CookieContainer = new CookieContainer();
String username = txtUserName.Text;
String password = txtPassword.Text;
String encoded = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(username + ":" + password));
request.Headers.Add("Authorization", "Basic " + encoded);
request.ContentLength = 0;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8);
String resultData = reader.ReadToEnd();
bool result = false;
result = Convert.ToBoolean(resultData);
return result;
我想我会需要认证头发送到所有需要是安全的,通过authentciation那些Web API请求。
I assume I will need to send authentication header to all of those web api requests that needs to be secure and pass through authentciation.
有没有一种方法来认证头附加到我送,甚至一组请求的每个请求?
请注意:大多数的Web API请求都是通过调用的JQuery
Is there a way to attach authentication header to every request that I send or even to a set of requests? Please note: most of the Web API requests are invoked through JQuery.
也请让我知道,如果这是不推荐的实施办法。
Also please let me know if this is not recommended approach of implementation.
问候,
Abhilash
推荐答案
你能与尝试以下request.Headers.Add(授权,基本+ EN codeD)的code就地;
Can you try with below code inplace of "request.Headers.Add("Authorization", "Basic " + encoded);" .
request.Headers.Add(HttpRequestHeader.Authorization, "Basic " +
Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes("user:password")));
这篇关于如何发送认证头在ASP.Net了一套Web请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!