C# 如何在不使用 ping 的情况下检查 Web 服务是否已启动并正在运行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10206951/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 12:53:02  来源:igfitidea点击:

How to check if a web service is up and running without using ping?

c#wcfweb-servicesmethodsping

提问by bebojoor

How can i check if a method in a web service is working fine or not ? I cannot use ping. I still want to check any kind of method being invoked from the web service by the client. I know it is difficult to generalize but there should be some way.

如何检查 Web 服务中的方法是否正常工作?我无法使用 ping。我仍然想检查客户端从 Web 服务调用的任何类型的方法。我知道很难概括,但应该有一些方法。

回答by Rumplin

just use try catch inside the method of your webservice and log exceptions to a log file or to the event log. Example:

只需在 Web 服务的方法中使用 try catch 并将异常记录到日志文件或事件日志中。例子:

[OperationContract]
 public bool isGUID(string input)
{
    bool functionReturnValue = false;

    try
    {
        Guid guid;
        functionReturnValue = Guid.TryParse(input, guid);
    }
    catch (Exception ex)
    {
        Log.WriteServerErrorLog(ex);
    }

    return functionReturnValue;
}

You don't need to ping the webservice, but instead ping the server with a watchdog service or something. There is no need to "ping" the webservice. I also think you don't need to do this anyway. Either your webservice works or it doesn't because of bad code.

您不需要ping webservice,而是使用看门狗服务或其他东西ping服务器。无需“ping”网络服务。我也认为你不需要这样做。要么您的网络服务正常工作,要么由于代码错误而无法正常工作。

回答by 18446744073709551615

You may try curl. It's a Linux tool, should be there in Cygwin too.

你可以试试curl。它是一个 Linux 工具,在 Cygwin 中也应该有。

$ curl http://google.com
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>301 Moved</TITLE></HEAD><BODY>
<H1>301 Moved</H1>
The document has moved
<A HREF="http://www.google.com/">here</A>.
</BODY></HTML>

There are lots of options; examples can be found in the 'net.

有很多选择;例子可以在'net.

回答by Louis Kottmann

As I see it, you have 2 options:

在我看来,您有两个选择:

  • If you can access the server it is running on, Log every call (and exceptions thrown).
    Read the log file with a soft like baretailthat updates as the file is being written.

  • If you can't access the server, then you have to make the webservice write that log remotely to another computer you have access to.
    Popular loggers have this functionality built in. (Log4Net, ...)

  • 如果您可以访问运行它的服务器,请记录每个调用(和抛出的异常)。
    使用像baretail这样的软件读取日志文件,该软件会在写入文件时更新。

  • 如果您无法访问服务器,则必须让 Web 服务将该日志远程写入您有权访问的另一台计算机。
    流行的记录器内置了此功能。(Log4Net,...)

回答by The Pig's Ear

I use this method and it works fine :

我使用这种方法,它工作正常:

public bool IsAddressAvailable(string address)
{
    try
    {
        System.Net.WebClient client = new WebClient();
        client.DownloadData(address);
        return true;
    }
    catch
    {
        return false;
    }
}

回答by John Saunders

The only way to know if a web service method is working "fine" is to call the method and then to evaluate whether the result is "fine". If you want to keep a record of "fine" vs. time, then you can log the result of the evaluation.

了解 Web 服务方法是否“正常”工作的唯一方法是调用该方法,然后评估结果是否“正常”。如果您想保留“罚款”与时间的记录,那么您可以记录评估结果。

There's no more general way to do this that makes any sense. Consider:

没有更通用的方法可以做到这一点。考虑:

  1. You could have code that creates an HTTP connection to the service endpoint, but success doesn't tell you whether the service will immediately throw an exception as soon as you send it any message.
  2. You could connect and send it an invalid message, but that doesn't tell you much.
  3. You could connect and send it a valid message, then check the result to ensure that it is valid. That will give you a pretty good idea that when a real client calls the service immediately afterwards, the real client should expect a valid result.
  4. Unless the service takes that as an opportunity to crash, just to spite you!
  1. 您可能拥有创建到服务端点的 HTTP 连接的代码,但成功并不会告诉您服务是否会在您向其发送任何消息后立即抛出异常。
  2. 您可以连接并向其发送无效消息,但这并不能告诉您太多信息。
  3. 您可以连接并向其发送有效消息,然后检查结果以确保其有效。这会给你一个很好的想法,当一个真实的客户端在之后立即调用服务时,真实的客户端应该期待一个有效的结果。
  4. 除非服务将其视为崩溃的机会,否则只是为了欺负您!

The best technique would be to use WCF tracing (possibly with message-level tracing) to log what actually happens with the service, good or bad. A human can then look at the logs to see if they are "fine".

最好的技术是使用 WCF 跟踪(可能使用消息级跟踪)来记录服务实际发生的情况,无论好坏。然后,人类可以查看日志以查看它们是否“正常”。

回答by CS Smit

You can write your self a little tool or windows service or whatever you need then look at these 2 articles:

您可以为自己编写一个小工具或 Windows 服务或任何您需要的东西,然后查看这两篇文章:

C#: How to programmatically check a web service is up and running?

C#:如何以编程方式检查 Web 服务是否已启动并正在运行?

check to if web-service is up and running - efficiently

检查网络服务是否已启动并正在运行 - 有效

EDIT: This was my implementation in a similar scenario where I need to know if an external service still exists every time before the call is made:

编辑:这是我在类似场景中的实现,每次调用之前我都需要知道外部服务是否仍然存在:

bool IsExternalServiceRunning
    {
        get
        {
            bool isRunning = false;
            try
            {
                var endpoint = new ServiceClient();
                var serviceUri  = endpoint.Endpoint.Address.Uri;
                var request = (HttpWebRequest)WebRequest.Create(serviceUri);
                request.Timeout = 1000000;
                var response = (HttpWebResponse)request.GetResponse();
                if (response.StatusCode == HttpStatusCode.OK)
                    isRunning = true;
            }
            #region
            catch (Exception ex)
            {
                // Handle error
            }
            #endregion
            return isRunning;
        }
    }

回答by Mark Walker

Powershell is by far an easy way to 'ping' a webservice endpoint.

到目前为止,Powershell 是一种“ping”网络服务端点的简单方法。

Use the following expression:

使用以下表达式:

Test-NetConnection -Port 4408 -ComputerName 192.168.134.1

Here is a failure response for a port that does not exist or is not listening;

这是对不存在或未侦听的端口的失败响应;

WARNING: TCP connect to 192.168.134.1:4408 failed
ComputerName           : 192.168.134.1
RemoteAddress          : 192.168.134.1
RemotePort             : 4408
InterfaceAlias         : Ethernet0
SourceAddress          : 192.168.134.1
PingSucceeded          : True
PingReplyDetails (RTT) : 0 ms
TcpTestSucceeded       : False

Here is a success result if the address/port is listening and accessible:

如果地址/端口正在侦听且可访问,则这是一个成功的结果:

ComputerName     : 192.168.134.1
RemoteAddress    : 192.168.134.1
RemotePort       : 4407
InterfaceAlias   : Ethernet0
SourceAddress    : 192.168.134.1
TcpTestSucceeded : True