C#如果控制器中存在过滤条件,mvc 5退出
我正在尝试擦干我的代码。我有一个控制器,它一次又一次地重复相同的代码位,但我无法移动到新方法,因为重复的代码包含一个return语句 下面是一个代码示例C#如果控制器中存在过滤条件,mvc 5退出,c#,.net,asp.net-mvc,C#,.net,Asp.net Mvc,我正在尝试擦干我的代码。我有一个控制器,它一次又一次地重复相同的代码位,但我无法移动到新方法,因为重复的代码包含一个return语句 下面是一个代码示例 public class ExampleController : Controller { private Authorizer _authorizer = new Authorizer(); public ActionResult Edit(int id) { //Repeated Code Start
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时。方法编辑也退出
有没有一种方法可以让助手方法在某个路径中返回ActionResult,但如果为null或其他情况,则允许在主路径上继续?这是使用ActionFilter的适当位置,通过正确应用它,您甚至不需要在控制器操作中检查,如果过滤器没有通过要求,那么它将设置响应,并且控制器操作将不会首先被调用
这里有一个链接可以帮助您:您可以使用ActionFilter来执行代码、记录错误等redirects@Wizard只需创建一个返回布尔值的方法。如果为true,则返回view,否则执行您想要执行的操作。@user123456这不会解决干燥问题。因为我需要在每一步中重复处理代码action@StephenMuecke是的,这是我需要指出的方向。好的,我会检查一下。您知道我是否可以将参数传递到actionFilter中吗?是的,可以在构造函数中添加参数,您还可以使用HttpContext.Items将数据从筛选器传递到控制器。