我正在编写一个 ASP.NET MVC 3 应用程序,我发现自己在我的操作方法中经常写这行代码:
var user = _session.Single<User>(u => u.UserName == User.Identity.Name);
(显然与AuthorizeAttribute
一起使用)
还有其他一些经常重复的事情,但这个是最突出的,我最终有 3 个彼此相邻的操作,每个都需要检索授权用户。
所以这需要干燥:
我应该编写一个
ApplicationContoller
,所有其他 Controller 都从中继承并公开一个User
属性,还是应该将其添加到我的IAdminService
并将其公开为方法?在 ASP.NET MVC 中,ApplicationController 是应该避免还是应该接受的东西?
最佳答案
如果您发现自己在重复此逻辑,那么针对 User 类型的自定义模型绑定(bind)器可能会有所帮助:
public class UserModelBinder : DefaultModelBinder
{
private readonly ISession _session;
public UserModelBinder(ISession session)
{
_session = session;
}
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var username = controllerContext.HttpContext.User.Identity.Name;
return _session.Single<User>(u => u.UserName == username);
}
}
一旦注册了 Binder ,您的 Controller 操作可能如下所示:
[Authorize]
public ActionResult Foo(User user)
{
// ...
}
关于asp.net-mvc - 干燥 ASP.NET MVC 操作 : ApplicationController or Service?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5601189/