使用HttpClient获取401计划任务

时间:2015-09-02 19:50:36

标签: c# dotnet-httpclient

在本地计算机上运行远程服务时效果很好。但是,当我部署控制台应用程序并尝试作为计划任务运行时,我在此呼叫中获得了401。可能与:Unable to authenticate to ASP.NET Web Api service with HttpClient

有关

端点正在使用https。当我在小提琴手中捕捉到电话时,它说:

No Proxy-Authorization Header is present.
No Authorization Header is present.

这里是401中的响应标题:

HTTP/1.1 401 Unauthorized
Content-Type: text/html
Server: Microsoft-IIS/7.5
WWW-Authenticate: Negotiate
WWW-Authenticate: NTLM
X-Powered-By: ASP.NET
Date: Wed, 02 Sep 2015 19:19:25 GMT
Content-Length: 1293
Proxy-Support: Session-Based-Authentication

这是客户端代码:

public async Task<ApiResult<string>> GetStuff(int id)
{
    var queryBuilder = new UriBuilder(BaseUrl);
    queryBuilder.Path += string.Format("/Stuff/{0}", id);

    using (var client = new HttpClient(new HttpClientHandler()
    {
        UseDefaultCredentials = true,
        PreAuthenticate = true,
    }))
    {
        client.BaseAddress = new Uri(BaseUrl);
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        var response = await client.GetAsync(queryBuilder.Uri.ToString());
        if (response.IsSuccessStatusCode)
        {
            var data = await response.Content.ReadAsAsync<string>();
            if (data == null)
            {
                return new ApiResult<string>
                {
                    Success = false,
                    Message = string.Format("No stuff found for id.  id={0}", id),
                    Value = data
                };
            }
            return new ApiResult<string>
            {
                Success = true,
                Message = "",
                Value = data
            };
        }
        else
        {
            var message = string.Format("Could not get stuff by id. id={0}, reasonPhrase={1},  ", id, response.ReasonPhrase);
            return new ApiResult<ShippingPreferences>
            {
                Success = false,
                Message = message,
            };
        }
    }
}

0 个答案:

没有答案