【发布时间】:2015-10-07 18:57:21
【问题描述】:
我有两个应用程序。一个是 ASP.NET Web Api,另一个是我从中调用 API 的控制台应用程序。调试时我总是得到 401.2 响应。 Fiddler 回馈这个响应
由于身份验证标头无效,您无权查看此页面。
我的问题是如何配置 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 Web 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 Web 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;
}
【问题讨论】:
-
这成功了匿名身份验证(最高投票答案)stackoverflow.com/questions/11687711/…。 Windows 身份验证呢?我是否必须为 HttpClient 请求提供一些标头?
-
您必须传递您的 Web api 正在寻找的标头。您的 web api 是否有任何授权过滤器?如果是,那么您必须检查您的 web api 正在寻找的详细信息。
-
UseDefaultCredentials 应该足以从控制台应用程序执行 Windows 身份验证。我刚刚对其进行了测试,它适用于 HttpListener 托管服务器。 AuthenticationManager 类负责使用适当的 Authorization 标头响应 www-authenticate 标头。
标签: c# authentication asp.net-web-api dotnet-httpclient