我正试图干掉我的代码。我有一个控制器,它一次又一次地重复相同的代码位,但我无法移动到新方法,因为重复的代码包含一个return语句。
下面是一个代码示例
public class ExampleController : Controller
{
private Authorizer _authorizer = new Authorizer();
public ActionResult Edit(int id)
{
//Repeated Code Start
var result = _authorizer.EditThing(id);
if (result.CanEditPartA)
{
//log attempted bad access
//Other repeted things
return View("error", result.Message);
}
//Repeated Code End
//unique logic to this action.
return View();
}
public ActionResult Edit1(int id, FormCollection collection)
{
//Repeated Code Start
var result = _authorizer.EditThing(id);
if (result.CanEditPartA)
{
//log attempted bad access
//Other repeted things
return View("error", result.Message);
}
//Repeated Code End
//unique logic to this action.
try
{
return RedirectToAction("Index");
}
catch
{
return View();
}
}
}
public class Authorizer
{
// check a bunch of things and determine if person can to something
public Result EditThing(int thingID)
{
//get thing from DB
//logic of thing compared to current user
//Create Result basied on bussness Logic
return new Result();
}
public class Result
{
public bool CanEditPartA { get; set; }
public bool CanEditPartB { get; set; }
public bool CanEditPartC { get; set; }
public string Message { get; set; }
}
}
}
这个例子在我的实际问题“重复代码”中缩短了很多
var result = _authorizer.EditThing(id);
if (result.CanEditPartA)
{
//log attempted bad access
//Other repeted things
return View("error", result.Message);
}
我希望能做这样的事情
public ActionResult Edit(int id)
{
if (CanUserEditPartA(id) != null)
{
return CanUserEditPartA(id);
}
//unique logic to this action.
return View();
}
private ActionResult CanUserEditPartA(int id)
{
var result = _authorizer.EditThing(id);
if (result.CanEditPartA)
{
//log attempted bad access
//Other repeted things
return View("error", result.Message);
}
return null;
}
但问题是当我返回null时。Methoded Edit也退出。
有没有一种方法可以让助手方法在某个路径中返回ActionResult,但如果为null或其他情况,则允许在主路径上继续?