需要在c#中的标准try/catch函数中包装函数

Bra*_*don 3 c# asp.net delegates anonymous-function

我知道有很多委托/功能示例,但我找不到任何适合我的例子,或者我只是不理解它们.

我正在使用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
Run Code Online (Sandbox Code Playgroud)

这是我正在使用的控制器方法/功能之一

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);
}
Run Code Online (Sandbox Code Playgroud)

我希望能够以某种方式将特定函数转换为变量以传递到通用代码中.我看过代表和匿名函数,但是直到你自己完成它才会让人感到困惑.

Raw*_*ing 6

将以下内容放在可访问的位置:

public static ActionResult SafeViewFromModel(
    Action<ResponseDataModel> setUpModel)
{
    var model = new ResponseDataModel();
    try
    {
        setUpModel(model);
    }
    catch (Exception ex)
    {
        model.Error = true;
        model.Message = ex.ToString();
    }
    return View(model); 
}
Run Code Online (Sandbox Code Playgroud)

然后称之为:

public ActionResult MillRequestCoil()
{
    return MyHelperClass.SafeViewFromModel(model =>
    {
        string coilId = "CC12345";
        model.Data = new {
            Coil = coilId,
            M3 = "m3 message",
            M5 = "m5 message" };
        model.Message = string.Format("Coil {0} sent successfully", coilId);
    });
}
Run Code Online (Sandbox Code Playgroud)