检查状态码C#

时间:2014-12-09 01:11:57

标签: c# if-statement http-status-codes

我需要一种方法来根据请求后返回的状态代码运行一些if语句。例如,如果返回400错误,我想重定向到登录页面。我需要一些关于如何检查状态代码并将该信息包含在if语句中的想法。像

这样的东西

如果() {

} 其他 {

}

我只需要将记录包括在我的if中。

2 个答案:

答案 0 :(得分:2)

您可以使用HttpWebResponse.StatusCode属性。

http://msdn.microsoft.com/en-us/library/system.net.httpwebresponse.statuscode%28v=vs.110%29.aspx

 public static void GetPage(String url) 
    {
        try 
          { 
                // Creates an HttpWebRequest for the specified URL. 
                HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url); 
                // Sends the HttpWebRequest and waits for a response.
                HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse(); 
                if (myHttpWebResponse.StatusCode == HttpStatusCode.OK)
                   Console.WriteLine("\r\nResponse Status Code is OK and StatusDescription is: {0}",
                                        myHttpWebResponse.StatusDescription);
                // Releases the resources of the response.
                myHttpWebResponse.Close(); 

            } 
        catch(WebException e) 
           {
                Console.WriteLine("\r\nWebException Raised. The following error occured : {0}",e.Status); 
           }
        catch(Exception e)
        {
            Console.WriteLine("\nThe following Exception was raised : {0}",e.Message);
        }
    }

答案 1 :(得分:0)

就像上面提到的评论一样,我不确定你正在做什么类型的项目。但是,在我的MVC项目中,我在Web.config文件中处理此问题,在system.web元素中有几行,如:

<customErrors mode="On" defaultRedirect="~/Error/Error">
  <error statusCode="404" redirect="~/Error/Error404" />
</customErrors>
相关问题