对.NET Web Api服务的Web请求得到401未经授权的错误
本文关键字:Web 授权 错误 请求 NET Api 服务 | 更新日期: 2023-09-27 18:20:54
我有一个web api服务,我想让另一个.Net应用程序向它发出web请求,但在这样做时我会收到以下错误:
"远程服务器返回错误:(401)未经授权。"
只是为了澄清一下,这是两个单独的.net应用程序,它们试图进行通信。
以下是客户端.Net c#应用程序的代码,该应用程序试图向另一个web api服务发出web请求:
public string MakeWebRequest()
{
var requestUrl = "http://localhost:8081/api/Tests/results";
var request = WebRequest.Create(requestUrl);
var username = "test";
var password = "test";
SetBasicAuthHeader(request, username, password);
var postData = "thing1=hello";
postData += "&thing2=world";
var data = Encoding.ASCII.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/json";
request.ContentLength = data.Length;
//request.Expect = "application/json";
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
string text;
var response = (HttpWebResponse)request.GetResponse();
using (var sr = new StreamReader(response.GetResponseStream()))
{
text = sr.ReadToEnd();
}
return null;
}
public static void SetBasicAuthHeader(WebRequest request, String userName, String userPassword)
{
string authInfo = userName + ":" + userPassword;
authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
request.Headers["Authorization"] = "Basic " + authInfo;
}
这是.Net c#webapi服务的代码,它应该从另一个应用程序接收web请求:
[RoutePrefix("api/Tests")]
public class TestsApiController : ApiController
{
[POST("results")]
[AcceptVerbs("POST")]
[HttpPost]
[BasicAuthAuthorize(Roles="Admin")]
public JObject resultsFinished()
{
//do something
}
}
这是我创建的基本身份验证属性,它甚至不会受到客户端服务的攻击。
public class BasicAuthAuthorizeAttribute : AuthorizeAttribute
{
private const string BasicAuthResponseHeader = "WWW-Authenticate";
private const string BasicAuthResponseHeaderValue = "Basic";
public override void OnAuthorization(HttpActionContext actionContext)
{
try
{
AuthenticationHeaderValue authValue = actionContext.Request.Headers.Authorization;
if (authValue != null && !String.IsNullOrWhiteSpace(authValue.Parameter) && authValue.Scheme == BasicAuthResponseHeaderValue)
{
var parsedCredentials = ParseAuthorizationHeader(authValue.Parameter);
if (parsedCredentials != null)
{
if (parsedCredentials.Username == IoC.Username && parsedCredentials.Password == IoC.Password)
return;
}
}
}
catch (Exception)
{
//actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
actionContext.Response.Headers.Add(BasicAuthResponseHeader, BasicAuthResponseHeaderValue);
return;
}
}
private Credentials ParseAuthorizationHeader(string authHeader)
{
string[] credentials = Encoding.ASCII.GetString(Convert.FromBase64String(authHeader)).Split(new[] { ':' });
if (credentials.Length != 2 || string.IsNullOrEmpty(credentials[0]) || string.IsNullOrEmpty(credentials[1]))
return null;
return new Credentials() { Username = credentials[0], Password = credentials[1], };
}
}
//Client credential
public class Credentials
{
public string Username { get; set; }
public string Password { get; set; }
}
尝试使用fiddler之类的工具来排除发送到web服务的内容:
http://www.telerik.com/fiddler