HttpClient使用Windows身份验证方式发送Get请求

业务需求:需要在一个C#控制台应用程序中调用某一个网站的一个页面,以便定期执行这个网站下面的一些方法。

刚开始是这么写的:

public class HttpHelper
{
	public static string apiUrl = CommonHelper.GetAppSettingAttribute("apiUrl");
	public static string apiKey = CommonHelper.GetAppSettingAttribute("apiKey");
	
	public static (bool isSuccess, string statusCode) Get()
	{
		HttpClient client = new HttpClient();

		client.DefaultRequestHeaders.Add("apiKey", apiKey);
		var response = client.GetAsync(apiUrl).Result;
        response.EnsureSuccessStatusCode();
		if (response.StatusCode == HttpStatusCode.OK)
		{
			return (true, ((int)response.StatusCode).ToString());
		}
		else
		{
			return (false, ((int)response.StatusCode).ToString());
		}
	}
}

但是结果访问不成功,response.StatusCode返回401

异常提示:响应状态代码不指示成功: 401 (Unauthorized)

查找原因,发现该网站是Windows集成身份验证方式,即该网站使用域账户登录。

尝试在IIS中禁掉Windows身份验证方式,开启匿名身份验证方式

此时网站访问成功,StatusCode返回200,但网站下面的方法并没有被执行。并且实际的生产环境不能随意更改IIS的设置,这样修改可能会导致用户无法正常访问网站。

研究好久,修改代码如下:

public class HttpHelper
{
	public static string apiUrl = CommonHelper.GetAppSettingAttribute("apiUrl");
	public static string apiKey = CommonHelper.GetAppSettingAttribute("apiKey");
	public static string username = CommonHelper.GetAppSettingAttribute("username");
	public static string pwd = CommonHelper.GetAppSettingAttribute("password");

	public static (bool isSuccess, string statusCode) Get()
	{
		HttpClientHandler handler = new HttpClientHandler();
		handler.Credentials = new NetworkCredential(username, pwd);
		HttpClient client = new HttpClient(handler);
		client.DefaultRequestHeaders.Add("apiKey", apiKey);
		var response = client.GetAsync(apiUrl).Result;
		response.EnsureSuccessStatusCode();
		if (response.StatusCode == HttpStatusCode.OK)
		{
			return (true, ((int)response.StatusCode).ToString());
		}
		else
		{
			return (false, ((int)response.StatusCode).ToString());
		}
	}
}

终于成功!就是加入了域账户的账号和密码。

记录一下。 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值