如何处理WebClient响应以向用户显示错误消息?

时间:2017-06-01 16:38:22

标签: c# asp.net-mvc asp.net-web-api

我正在研究一个调用Web API的MVC Web App。在我的创建(POST)方法中,用户将输入数据库中某些用户的电子邮件地址。只有在数据库中尚不存在电子邮件时,我才会检查是否输入电子邮件。如果它已经存在,我希望能够向用户显示错误消息“电子邮件已存在”。

我不知道如何处理响应,以便在用户无法创建批准者时向用户显示错误消息?我正在尝试try-catch案例,但它无效。我有ViewBag.Message = error我试图在我的索引视图中显示它失败时。但没有任何表现。当我调试时,当数据库中存在电子邮件时,它甚至不会转到catch,它只会将我带到索引视图。

public ActionResult Create([Bind(Include = "Email,FirstName,LastName")] ApprovedUsers approvedUsers)
{
    try
    {
        using (WebClient client = new WebClient())
        {
            token = Session.GetDataFromSession<string>("access_token");
            client.Headers.Add("authorization", "Bearer " + token);
            byte[] response = client.UploadValues(apiUrl, "POST", new NameValueCollection()
            {
                { "Email", approvedUsers.Email },
                { "FirstName",approvedUsers.FirstName },
                { "LastName",approvedUsers.LastName }
            });

            string result = System.Text.Encoding.UTF8.GetString(response);
            return RedirectToAction("Index");
        }
    }
    catch
    {
        return RedirectToAction("Index", new { error = "Email exists" });
    }
}

索引操作

public ViewResult Index(string sortOrder, string currentFilter, string searchString, int? page, string error)
        {
            ViewBag.Message = error;

这是被调用的 API 方法。

public IHttpActionResult PostApprovedUsers(ApprovedUsers approvedUsers)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

if (!db.ApprovedUsers.Any(u => u.Email == approvedUsers.Email))
{
    db.ApprovedUsers.Add(approvedUsers);
    db.SaveChanges();
}
return CreatedAtRoute("DefaultApi", new { id = approvedUsers.Email }, approvedUsers);  

2 个答案:

答案 0 :(得分:0)

试试这个:

public ActionResult Create([Bind(Include = "Email,FirstName,LastName")] ApprovedUsers approvedUsers)
{ 
    try
    {
        using (WebClient client = new WebClient())
        {
            token = Session.GetDataFromSession<string>("access_token");
            client.Headers.Add("authorization", "Bearer " + token);
            byte[] response = client.UploadValues(apiUrl, "POST", new NameValueCollection()
            {
                { "Email", approvedUsers.Email },
                { "FirstName",approvedUsers.FirstName },
                { "LastName",approvedUsers.LastName }
            });

            string result = System.Text.Encoding.UTF8.GetString(response);            
        }
    }
    catch
    {
       TempData["Error"] = "Email Exists";});
    }

  RedirectToAction("Index");

 }

public ViewResult Index(string sortOrder, string currentFilter, string searchString, int? page, string error)
  {
      ViewBag.Message = TempData["Error"].ToString();
  }

答案 1 :(得分:0)

导致问题的是我的API。即使它无法创建重复的电子邮件,它也从未进入catch,因为如果电子邮件确实存在于数据库中,我没有返回错误的请求。

将我的API更改为此,然后它正常运行。

if (db.ApprovedUsers.Any(u => u.Email == approvedUsers.Email))
{
    return Content(HttpStatusCode.BadRequest, "Email exists already");
}
else
{
    db.ApprovedUsers.Add(approvedUsers);
}
   try
   {
      db.SaveChanges();
   }
   catch (DbUpdateException e)
   {
      if (ApprovedUsersExists(approvedUsers.Id))
       {
          return Conflict();
       }
       throw e;