2
我有兩個應用程序。一個是ASP.NET Web Api,另一個是我稱之爲API的控制檯應用程序。在調試時,我總是得到401.2的迴應。提琴手回覆此回覆ASP.NET Web API調用控制檯應用程序認證標頭
由於無效的驗證標頭,您無權查看此頁面。
我的問題是如何配置IIS Express以及如何在控制檯應用程序中設置頭以正確調用Web Api?我想進行Windows或匿名身份驗證。我還在IIS Express中啓用了Windows身份驗證。
控制檯應用程序代碼:
MachineStateModel model = new MachineStateModel();
model.DataType = "1";
model.MachineID = 1;
model.TimeStamp = DateTime.Now;
model.Value = "0";
HttpClientHandler handler = new HttpClientHandler() { UseDefaultCredentials = true };
using (var Client = new HttpClient(handler))
{
Client.BaseAddress = new Uri("http://localhost.fiddler:55308/");
Client.DefaultRequestHeaders.Accept.Clear();
Client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await Client.PostAsJsonAsync("api/machinestate", model);
if (response.IsSuccessStatusCode)
{
Console.WriteLine("Call is successful");
}
}
ASP.NET網絡API的web.config:
<system.web>
<compilation debug="true" targetFramework="4.5.2" />
<httpRuntime targetFramework="4.5.2" />
<customErrors mode="Off" />
<authentication mode="Windows"/>
<authorization>
<allow users="?"/>
</authorization>
ASP.NET網絡API控制器方法:
// POST api/values
public HttpResponseException Post([FromBody]MachineStateModel value)
{
XmlMStateStream CurrentStream = new XmlMStateStream();
CurrentStream.DateTime = value.TimeStamp;
CurrentStream.MachineID = value.MachineID;
CurrentStream.DataType = value.DataType;
CurrentStream.Value = value.Value;
HttpResponseMessage responsemessage = Request.CreateResponse(HttpStatusCode.OK, CurrentStream);
HttpResponseException response = new HttpResponseException(responsemessage);
return response;
}
這沒有爲匿名身份驗證招(投頂部的答案):HTTP://計算器。 com/questions/11687711/all-requests-getting-http-error-401-2-unauthorized-response。那麼Windows身份驗證呢?我是否需要爲HttpClient請求提供一些頭文件? –
您必須傳遞您的web api正在查找的標頭。你的web api是否有任何授權過濾器?如果是,那麼你必須檢查你的網頁api正在尋找的細節。 –
UseDefaultCredentials應該足以通過控制檯應用程序進行Windows身份驗證。我只是測試它,它對HttpListener託管的服務器起作用。 AuthenticationManager類負責使用適當的授權標頭響應www-authenticate標頭。 –