【问题标题】:Return status error to WebRequest向 WebRequest 返回状态错误
【发布时间】:2012-08-25 00:30:54
【问题描述】:

我用这样的WebRequest 调用远程操作:

var site = "http://remoteSite.com/controller/IsolateSite?url=xxx&target=in";
var request = (HttpWebRequest)WebRequest.Create(site);
var response = (HttpWebResponse)request.GetResponse();

if (response.StatusDescription == "OK")
{ /* code */ }
else
{ /* code */ }

在远程操作中,我返回一条消息或null(如果id 好不好)。

response.StatusDescription 始终等于"OK",即使操作返回null

如何强制将错误作为状态或检索消息(如"Cool.""Error.")?


远程操作示例:

public static string IsolateSite(string url, string target)
{
    var serverManager = new ServerManager();
    var isHttps = url.Contains("https");
    var regex = new Regex("^(http|https)://");
    var host = regex.Replace(url, "");
    var instance = serverManager.Sites.First(site => site.Bindings.Any(binding => binding.Host == host));
    var pool = instance.Applications[0].ApplicationPoolName;

    if ((pool.Contains("isolation") && target == "out") || (!pool.Contains("isolation") && target == "in"))
    {
        return "Error."; //or return null but the status code is OK so useless
    }

    //etc...

    return "Cool.";
}

【问题讨论】:

  • 示例操作在您想要返回错误案例的位置看起来如何?
  • 你的 response.StatusCode 是什么?
  • @Raj - OK (System.Net.HttpStatusCode)

标签: c# asp.net-mvc httpwebrequest


【解决方案1】:

errorcool 等 Httpstatus 代码无效,here 您可以找到所有状态代码。

与其在出错时返回字符串,不如抛出一个 HttpException:

throw new HttpException(500, "Error");

在这种情况下,我使用 http 响应状态代码 500(内部服务器错误)。

另一个考虑因素是查看 ASP.NET WebApi 来提供此类服务,我认为它比 Asp.NET MVC 控制器更适合。

【讨论】:

    【解决方案2】:

    只需将响应发送给 StreamReader,如下所示。

          var site = "http://remoteSite.com/controller/action/id";
          var request = (HttpWebRequest)WebRequest.Create(site);
          var response = (HttpWebResponse)request.GetResponse();
          StreamReader reader = new StreamReader(response.GetResponseStream());
           // This will contain the status of message e.g.    failed, ok etc.
          string resultStatus = reader.ReadToEnd(); 
    

    结果状态将为您提供错误状态和描述

    【讨论】:

      猜你喜欢
      • 2015-10-13
      • 2012-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多