ASP.NET Web API调用控制台应用程序认证标头
问题描述:
我有两个应用程序。一个是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;
}
答
尝试启用windowsAuthentication在IIS Express在\ My Documents文件\ IISExpress \ CONFIG \对ApplicationHost.config:
<system.webServer>
...
<security>
...
<authentication>
<windowsAuthentication enabled="true" />
</authentication>
...
</security>
...
</system.webServer>
这没有为匿名身份验证招(投顶部的答案):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标头。 –