我有一个web api服务,我想要另一个.Net应用程序发出Web请求,但是这样做会出现以下错误:
“远程服务器返回错误:(401)未经授权。”
只是为了澄清,这些是试图沟通的2个独立的.net应用程序。
以下是客户端.Net c#app尝试向其他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;
}
这是应该从其他应用程序接收Web请求的.Net c#web api服务的代码:
[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; }
}