从控制台应用程序身份验证标头调用ASP.NET Web Api

时间:2015-10-07 10:06:39

标签: c# authentication asp.net-web-api dotnet-httpclient

我有两个申请。一个是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;
    }

1 个答案:

答案 0 :(得分:0)

尝试在\ My Documents \ IISExpress \ config \ applicationhost.config中的IIS Express中启用windowsAuthentication:

<system.webServer>
...
  <security>
...
    <authentication>
      <windowsAuthentication enabled="true" />
   </authentication>
...
  </security>
...
</system.webServer>