0

我有一个控制器,它检查 url 列表并将 httpstatus 代码、描述和消息返回到视图。每次我调试我的解决方案时,它都会遍历 url 列表,但它只返回第一个 url 的状态。

如何返回所有 url 列表的状态?这是我的示例代码

        {

        string[] urls = {
      "http://www.google.com","http://www.34q34adf.com","http://aldlfaldkfk.com","http://www.bbc.com"

                        };

        foreach (string url in urls)

        {
            try
            {


                HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);


                HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();

                ViewBag.status_code = ((int)myHttpWebResponse.StatusCode);
                ViewBag.status_desc = myHttpWebResponse.StatusDescription;
                var current_code = ((int)myHttpWebResponse.StatusCode);

                if (current_code == 200)
                {
                    ViewBag.Image = "Images/green_light.png";
                    ViewBag.AlertType = "alert-success";
                }

                myHttpWebResponse.Close();

            }
            catch (WebException e)
            {
                string message = e.Message;

                if (e.Status == WebExceptionStatus.ProtocolError)
                {
                    HttpWebResponse hwr = (HttpWebResponse)e.Response;

                    ViewBag.status_code = ((int)hwr.StatusCode);
                    ViewBag.status_desc = hwr.StatusDescription;
                    var current_code = ((int)hwr.StatusCode);
                    ViewBag.status_desc = hwr.StatusDescription;
                    if (current_code != 200)
                    {
                        ViewBag.Image = "Images/red_light.png";
                        ViewBag.AlertType = "alert-error";
                    }
                }
            }
            catch (Exception e)
            {
                ViewBag.message = e.Message;
            }
        }

        return View();
    }

如何让我的视图显示所有 url 的状态?任何帮助将不胜感激。

4

1 回答 1

1

您应该创建一个 ViewModel 来保存 url 及其状态并将其列表传递给视图。

public class URLStatusVM
{
  public string URL { set;get;}
  public string Status { set;get;}
}

并在您的 Action 方法中

public ActionResult CheckIt()
{
   List<URLStatusVM> urlList=new List<URLStatusVM>();

   string[] urls = {"http://www.google.com","http://www.aaa.com"}
   foreach (string url in urls)
   {
     //Check the status using HttpWebRequest call here

     //Create an object of our view model and set the property values
     var item=new URLStatusVM();
     item.URL=url;
     item.Status="Some status text"; //replace with the status from web call

     //now add to our list
     urlList.Add(item);

    //your foreach loop ends here
   }
   return View(urlList);
}

现在将您的视图强类型化为 URLStatusVM 类的集合。

@model List<URLStatusVM>

@foreach(var item in Model)
{
 <p> @item.URL </p>
 <p> @item.Status </p>
}
于 2013-03-03T03:51:28.770 回答