我知道有很多委托/函数示例,但我找不到任何适合我的示例,或者我只是不理解它们。
我正在将 asp.net MVC 用于网站,并且该网站需要一些 Web 服务调用以使外部应用程序与我的应用程序交互。这些都需要一个函数来执行(去 db 等等),并且每次都返回一个相似的数据模型。我想将每个调用包装在 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);
}
我希望能够以某种方式将特定函数转换为变量以传递给通用代码。我看过代表和匿名函数,但在你自己做之前,这很令人困惑。