在不使用HttpRequest的情况下获取主机名 [英] Get host name without using HttpRequest

查看:262
本文介绍了在不使用HttpRequest的情况下获取主机名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的ASP.NET应用程序中运行后台作业"(定期,作为单独的线程).我需要主机名(DNS名称或IP)来执行任务.问题在于HttpContext.Current在这里可能不可用(它是NULL).

I want to run a "background job" in my ASP.NET application (periodically, as separate thread). And I need host name (DNS name or IP) to do my tasks. The problem is that the HttpContext.Current may be not available here (it's NULL).

是否可以通过不使用HttpContext.Current.Request.Url.Host来获取主机名.

Is there any way to get a host name in not using HttpContext.Current.Request.Url.Host.

推荐答案

当主机名在HttpContext.Request.Url.Host中可用时,这是主机名成为客户端发送的请求的一部分的结果.例如,向该页面提出请求:

When the host name is available in HttpContext.Request.Url.Host, it is a result of the host name being part of the request sent by the client. As an example, take a request to this page:


GET /questions/2164261/get-host-name-without-using-httprequest HTTP/1.1
Host: stackoverflow.com
...

在后台线程中运行时,没有请求上下文可用,并且实际上根本没有主机名的概念.您唯一的选择是将主机名存储在代码或配置中.

When running in a background thread, no request context is available, and there really is no concept of a host name at all. Your only alternative is to store the hostname within the code or in configuration.

稍微偏离主题:在Web应用程序中运行计划的任务会带来麻烦,而生成线程只能处理其中的一些任务.如果可能,请考虑从Windows服务运行计划的作业,该服务可能使用诸如 NCron 的框架构建a>.

Slightly off topic: Running scheduled tasks within a web application is asking for trouble, and spawning threads only deals with a few of them. If at all possible, consider running your scheduled jobs from a Windows service, possibly built using a framework like NCron.

这篇关于在不使用HttpRequest的情况下获取主机名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆