我有以下 Delete Action 方法,主要执行两个单独的任务:-
- 使用 API 调用从第三方应用程序中删除记录。
- 使用实体框架从我们自己系统上的数据库中删除一条记录。
我的操作方法如下:-
[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(int id)
{
var message = "";
var status = "";
var tag = "";
Resource resource = new Resource();
try
{
Rack rack = repository.FindRack(id);
tag = rack.Technology.Tag;
resource = repository.GetResource(rack.Technology.IT360ID.Value);
}
catch (NullReferenceException)
{
return Json(new
{
IsSuccess = "False"
}, JsonRequestBehavior.AllowGet);
}
catch (DbUpdateException)
{
return Json(new
{
IsSuccess = "AlreadyUsed"
}, JsonRequestBehavior.AllowGet);
}
using(var client = new WebClient())
{
var query = HttpUtility.ParseQueryString(string.Empty);
query["username"] = "testuser";
query["assetType"] = resource.ComponentDefinition.ComponentType.COMPONENTTYPENAME;
query["operation"] = "DeleteAsset";
query["assetName"] = resource.RESOURCENAME;
var url = new UriBuilder("http://win-spdev:8400/servlets/AssetServlet");
url.Query = query.ToString();
try
{
string xml = client.DownloadString(url.ToString());
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
status = doc.SelectSingleNode("/operation/operationstatus").InnerText;
message = doc.SelectSingleNode("/operation/message").InnerText;
}
catch (WebException ex)
{}
}
if (status.ToUpper() == "SUCCESS")
{
try
{
repository.DeleteRack(id, User.Identity.Name);
repository.Save();
return Json(new
{
IsSuccess = "True", id = id, description = tag
}, JsonRequestBehavior.AllowGet);
}
catch (NullReferenceException)
{
return Json(new
{
IsSuccess = "False"
}, JsonRequestBehavior.AllowGet);
}
catch (DbUpdateException)
{
return Json(new
{
IsSuccess = "AlreadyUsed"
}, JsonRequestBehavior.AllowGet);
}
}
return RedirectToAction("Delete", new
{
id = id
});
}
因为我使用实体框架来执行删除和 API 调用,所以我最终得到了单独的 try/catch 块。那么我的操作方法逻辑是否认为设计不佳,因为我在同一个操作方法中有多个 try/catch 块?我可以遵循什么更好的方法?