我目前正在编写一个由 mvc web api 服务器和 mvc 4 客户端组成的小应用程序,我遇到了一个问题,这已经困扰了我好几天了。
我有一个 ContactsController,其中包含:
[HttpPost]
public ActionResult AddContact(ContactModel model, HttpPostedFileBase image)
{
return ActionWrapper(() =>
{
if (model.InitializeFromCookie())
{
if (image != null)
{
model.ImageMimeType = image.ContentType;
model.Picture = new byte[image.ContentLength];
image.InputStream.Read(model.Picture, 0, image.ContentLength);
}
PostObject("api/contacts/postcontact", model);
RefreshCookie();
return RedirectToAction("Contacts", "Contacts");
}
else
{
return JsonRedirectResult(Url.Action("Login", "Users"));
}
});
}
模型派生自 AuthorizationContent。post对象方法:
[NonAction]
protected object PostObject(string apiUrl, object obj, object additionalData = null)
{
var query = additionalData != null ? additionalData.GetQueryString() : string.Empty;
apiUrl += query;
var action = _client.PostAsJsonAsync(apiUrl, obj);
action.Wait();
if (!action.Result.IsSuccessStatusCode)
{
var code = action.Result.StatusCode;
var error = action.Result.ReasonPhrase;
throw new ServerSideException(code, error);
}
else
{
return action.Result.Content.ReadAsAsync<object>().Result;
}
}
该方法即将调用webapi控制器的方法:
[AuthorizedOnly, HttpPost]
public void PostContact([FromBody]AuthorizationContent item, User authorizedUser)
{
var realItem = Mapper.Map<ContactModel, Contact>((ContactModel) item);
_contactService.AddContact(authorizedUser, realItem);
}
过滤器:
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
class AuthorizedOnly : ActionFilterAttribute
{
private ISessionService _sessionService;
private Session _userSession;
public ISessionService SessionService
{
get { return _sessionService ?? (_sessionService = NinjectWebCommon.Kernel.Get<ISessionService>()); }
}
public override void OnActionExecuting(HttpActionContext actionContext)
{
var auth = actionContext.ActionArguments.Values.FirstOrDefault() as AuthorizationContent;
if (auth == null)
{
throw new UnauthorizedException();
}
else
{
var user = SessionService.GetMemberBySessionCredentials(auth.Token, auth.UserName);
_userSession = user.Session;
if (SessionService.IsSessionValid(_userSession))
{
actionContext.ActionArguments["authorizedUser"] = user;
base.OnActionExecuting(actionContext);
}
else
{
throw new UnauthorizedException();
}
}
}
该代码适用于获取操作,但是当我尝试执行如上所示的帖子时,我总是收到服务器端异常说明
{状态代码:400,原因短语:
'无法将多个参数('item' 和 'authorizedUser')绑定到请求的内容。',版本:1.1,内容:System.Net.Http.StringContent,标头:{ Content-Type: text/plain; 字符集=utf-8 } }
问题 - 我如何声明authorizedUser 将来自过滤器和模型绑定器不应该在请求内容中查找它?对不起我的英语不好,提前谢谢你!