我有,我想其他.NET應用程序使Web請求發送到Web API服務,但是我發現了以下錯誤這樣做時:的Web請求的.NET Web API服務得到401未經授權錯誤
「」遠程服務器返回錯誤:(401)未經授權。「
只是爲了澄清,這些是2個獨立的.net應用程序試圖溝通。
下面是客戶端的.Net C#應用程序試圖使Web請求到其他Web API服務的代碼:
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;
}
而這裏的淨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; }
}
是我還是你發送**通過HTTP原始明文密碼* * –
抱歉忘記包含更多編碼密碼的代碼。上面的通知編輯。謝謝! – jre247
Web服務中可以運行「HelloWorld」或「Test」方法嗎?這可能是運行該服務的應用程序池的id的問題。 – Duston