业务需求:需要在一个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());
}
}
}
终于成功!就是加入了域账户的账号和密码。
记录一下。