我知道有很多委託/函數的例子,但我找不到任何適用於我的例子,或者我只是不理解它們。需要在c中的標準try/catch函數中包裝函數#
我爲網站使用asp.net MVC,並且該網站需要一些外部應用程序與我的應用程序進行交互的Web服務調用。這些都需要一個函數來執行(去db和whatnot),並且每次都返回一個類似的數據模型。我想在try/catch中包裝每個調用並填充模型。
這是每次調用都會發生的通用代碼。
var model = new ResponseDataModel();
try
{
//execute different code here
}
catch (Exception ex)
{
model.Error = true;
model.Message = ex.ToString();
}
return View(model); // will return JSON or XML depending on what the caller specifies
這是控制器方法/功能中的一個,我使用
public ActionResult MillRequestCoil()
{
var model = new ResponseDataModel();
try
{
/* edit */
//specific code
string coilId = "CC12345";
//additional code
model.Data = dataRepository.doSomethingToCoil(coilId);
//replaced code
//model.Data = new { Coil = coilId, M3 = "m3 message", M5 = "m5 message" };
model.Message = string.Format("Coil {0} sent successfully", coilId);
}
catch (Exception ex)
{
model.Error = true;
model.Message = ex.ToString();
}
return View(model);
}
我希望能夠將特定功能以某種方式轉換爲變量傳遞到通用代碼。我查看了代表和匿名函數,但直到你自己做,它纔會令人困惑。
你可以傳遞一個類型爲「Action」的對象給方法嗎?這可以讓你將真正的方法傳遞給'MillRequestCoil'等。不知道這是否可以在ASP.NET中工作。 – ChrisF
@ChrisF,你能舉個例子嗎?我想這就是我想要做的,但不知道該怎麼做。 – Brandon
現有答案顯示了我的建議。我對ASP.NET不熟悉,不知道我能建議的代碼是否可以工作。 – ChrisF