【发布时间】:2012-09-05 04:27:43
【问题描述】:
我正在实现一个 MVC 解决方案,该解决方案具有一些用于各种数据查询的 Web API 端点。我使用the techniques described in this post 将我的验证问题分离到服务层。
如果您想跳到具体问题,这篇文章的末尾有一个 TL;DR。
这是我的ApiController 代码:
[Authorize]
public class FriendsController : ApiController
{
private IItemService _service;
public FriendsController()
{
_service = new ItemService(new HttpModelStateWrapper(ModelState), new ViewModelRepository());
}
public FriendsController(IItemService service)
{
_service = service;
}
// GET api/friends
public IEnumerable<User> Get()
{
return _service.GetFriends(User.Identity.Name);
}
.
.
.
// POST api/friends
public void Post(Guid id)
{
var user = _service.AddFriend(User.Identity.Name, id); // Handles error and should update ViewModel
NotificationAsyncController.AddNotification(user);
}
}
_service.AddFriend(User.Identity.Name, id); 的代码如下所示:
public User AddFriend(string userName, Guid id)
{
try
{
return _repository.AddFriend(userName, id);
}
catch (Exception e)
{
_validationDictionary.AddError("AddFriend", e.Message);
return null;
}
}
而_validationDictionary 看起来像这样:
public class HttpModelStateWrapper : IValidationDictionary
{
private ModelStateDictionary ModelState;
public HttpModelStateWrapper(ModelStateDictionary ModelState)
{
this.ModelState = ModelState;
}
public void AddError(string key, string errorMessage)
{
if (ModelState != null)
ModelState.AddModelError(key, errorMessage);
}
public bool IsValid
{
get { return ModelState == null ? false : ModelState.IsValid; }
}
}
好吧,我发现如果_repository.AddFriend(userName, id); 引发错误并调用_validationDictionary.AddError("AddFriend", e.Message);,则_validationDictionary 中的ModelState 对象不会更新驻留在FriendsController 中的ModelState 对象。
也就是说,在调用AddError之后,HttpModelStateWrapper中的ModelState是无效的,但是一旦该方法返回并且范围返回到FriendsController,它的ModelState并没有更新,仍然有效!
TL;DR
如何获取已传递到 FriendsController 的 ctor 中的 HttpModelStateWrapper 的 ModelState 对象,使其更改反映在 FriendsController 的 ModelState 对象中?
【问题讨论】:
标签: c# error-handling asp.net-web-api service-layer asp.net-mvc-viewmodel