惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
aimingoo的专栏
aimingoo的专栏
IT之家
IT之家
N
Netflix TechBlog - Medium
MyScale Blog
MyScale Blog
雷峰网
雷峰网
T
Tailwind CSS Blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
T
The Blog of Author Tim Ferriss
S
Schneier on Security
C
CERT Recently Published Vulnerability Notes
Help Net Security
Help Net Security
云风的 BLOG
云风的 BLOG
GbyAI
GbyAI
I
InfoQ
H
Help Net Security
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
酷 壳 – CoolShell
酷 壳 – CoolShell
G
GRAHAM CLULEY
Blog — PlanetScale
Blog — PlanetScale
G
Google Developers Blog
I
Intezer
大猫的无限游戏
大猫的无限游戏
AWS News Blog
AWS News Blog
Recent Announcements
Recent Announcements
Google DeepMind News
Google DeepMind News
Spread Privacy
Spread Privacy
博客园_首页
宝玉的分享
宝玉的分享
量子位
T
Threatpost
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Security Latest
Security Latest
C
Cybersecurity and Infrastructure Security Agency CISA
SecWiki News
SecWiki News
H
Hackread – Cybersecurity News, Data Breaches, AI and More
博客园 - Franky
C
CXSECURITY Database RSS Feed - CXSecurity.com
T
The Exploit Database - CXSecurity.com
T
Tenable Blog
Know Your Adversary
Know Your Adversary
P
Proofpoint News Feed
The Register - Security
The Register - Security
V2EX - 技术
V2EX - 技术
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Last Week in AI
Last Week in AI
L
LangChain Blog
T
Tor Project blog
Stack Overflow Blog
Stack Overflow Blog
月光博客
月光博客

博客园 - great wang

深入理解OAuth 2.0(是一种授权机制,主要用来颁发令牌) 最全的.NET Core跨平台微服务学习资源 飞鱼星路由器端口映射/端口转发的设置步骤及注意事项 .net实现微信公众账号接口开发 飞鱼星路由器端口映射/端口转发的设置步骤及注意事项 SSRS:之为用户“NT AUTHORITY\NETWORK SERVICE”授予的权限不足,无法执行此操作。 (rsAccessDenied) - great wang ASP.NET页面重复加载的问题之<img src="#" /> [转]SQL2008关于c001f011的错误解决办法 [转]Linq查询DataTable,DataRow SSRS:服务器更名后,ReportingService无法使用和登录的解决办法 误删除系统帐户且SA被禁用,如何修复?单用户模式登录可解决。 使用AspNetPager控件多个参数Url重写功能问题 [转]js动态创建json类型 [转]LINQ分组查询统计(group by、count) [转]js 字符串日期 yyyy-MM-dd 转化为 date [转]并发数的计算 [转]使用SQL语句取相关日期(当月天数,当月第一天,当月最后一天,本年最后一天,当月第一个星期) 日期转字符串 ASP.NET系统整合DiscuzNT3.6之注意事项 SSRS:首次加载或过一段时间后(默认20分钟)再加载时第一次就非常慢。
windows服务与控制台应用程序之HttpWebResponse的使用
great wang · 2012-10-16 · via 博客园 - great wang

  HttpWebRequest+HttpWebResponse经常会被使用在控制台应用程序中,比如检测页面是否正常或定期访问。随着需求的变化,我们可能需要将此功能迁移到windows服务中执行,windows服务不会被轻易的误关闭。

  一、在控制台应用程序中使用HttpWebResponse:

HttpWebRequest request = WebRequest.Create(urlPath) as HttpWebRequest;

//如下三行效果一样,若全被注释了,那么将会看到401的异常信息。
request.UseDefaultCredentials = true;              
//request.Credentials = CredentialCache.DefaultNetworkCredentials;
//request.Credentials = CredentialCache.DefaultCredentials;

// Get the response.
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
    if (response.StatusCode == HttpStatusCode.OK)
    {
        // Display the status.
        WriteLog(response.StatusDescription);
        // Get the stream containing content returned by the server.
        using (Stream dataStream = response.GetResponseStream())
        {
            // Open the stream using a StreamReader for easy access.
            using (StreamReader reader = new StreamReader(dataStream))
            {
                //Read the content.
                string responseFromServer = reader.ReadToEnd();
                //Display the content.
                Console.WriteLine(responseFromServer);
                Console.WriteLine(DateTime.Now.ToString() + " Successed.");
                WriteLog("Successed");
            }
        }
    }
    else
    {
        WriteLog("status code is not Ok it was" + response.StatusCode.ToString());
    }
}

  结论:以上代码可以正常运行,因为控制台应用程序是基于当前登录的用户身份去访问。
二、windows服务中使用HttpWebResponse
  我们直接将以上代码迁移到windows服务中,理论上可以正常运行的。可实际情况出现了如下错误:

System.Net.WebException: 远程服务器返回错误: (401) 未经授权。
   在 System.Net.HttpWebRequest.GetResponse()


  那么,我们如何解决呢?我们使用的是本地IIS的站点。先引用一个网友的一段话:

Windows Service application run under the LocalSystem account by default, whereas your console app runs under your user account, you may therefore be meeting permission problems (windows firewall?)

You should run the service under the administrator account to see if this resolves your issue.

  试想一下,我们不难理解,windows服务程序是基于本地系统帐户运行的。 
  其实关键部分还是设置UseDefaultCredentials或者Credentials,代码中的三种方法是有效的。这三种方法的差别:

1. Credentials = CredentialCache.DefaultCredentials; 表示在发送请求会带上当前用户的身份验证凭据。
2. UseDefaultCredentials = true; 此方法在内部会调用前面的方法,因此与前面的方法是一样的。
3. Credentials = CredentialCache.DefaultNetworkCredentials; 是在.NET 2.0中引用的新方法。


  解决方法一,修改凭证格式,指定用户名和密码:

request.UseDefaultCredentials = true;

修改为:

NetworkCredential credentials = new NetworkCredential("username", "pwd");

request.Credentials = credentials;