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

本文关键字:调用 NET Web Api 身份验证 控制台 应用程序 ASP | 更新日期: 2023-09-27 18:16:20

我有两个应用程序。一个是ASP。另一个是控制台应用程序,我从它调用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;
    }

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

尝试在IISExpress中启用windowsAuthentication 'My Documents'IISExpress'config'applicationhost.config:

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