繁体   English   中英

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

[英]ASP.NET Web Api call from console application authentication header

我有两个应用程序。 一个是ASP.NET Web Api,另一个是控制台应用程序,我从中调用API。 调试时,我总是得到401.2响应。 提琴手给这个回应

由于身份验证标题无效,因此您无权查看此页面。

我的问题是如何配置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;
    }

尝试在IIS Express中的\\ My Documents \\ IISExpress \\ config \\ applicationhost.config中启用Windows身份验证:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM