问题描述
下面的属性用于限制使用一个动作一个Ajax请求:
The following attribute is used to restrict use of an action to an ajax request:
public class AjaxRequestAttribute : ActionMethodSelectorAttribute
{
public override bool IsValidForRequest(ControllerContext controllerContext, System.Reflection.MethodInfo methodInfo)
{
return controllerContext.HttpContext.Request.IsAjaxRequest();
}
}
我有以下的控制器操作方法定义的:
I have the following controller action methods defined:
[AjaxRequest]
public ActionResult Login()
{
...
}
[HttpPost, AjaxRequest]
public ActionResult Login(LoginModel model, string returnUrl)
{
...
}
在阿贾克斯后制成出现以下错误:
The following error occurs when the ajax post is made:
采取行动的当前请求登录控制器类型
AgentController是下面的操作方法之间暧昧:
System.Web.Mvc.ActionResult登录()的类型
NappWebsiteMvc.Controllers.AgentController System.Web.Mvc.ActionResult
登录(NappWebsiteMvc.Models.Agent.LoginModel,System.String)的类型
NappWebsiteMvc.Controllers.AgentController
看来,HttpPost属性使用附加属性时被忽略。如果我从两种方法去除AjaxRequest属性,那么code工作。
It seems that the HttpPost attribute is ignored when using the additional attribute. If I remove the AjaxRequest attribute from the two methods, then the code works.
应该是什么的正确实施?谢谢!
What should be the correct implementation? Thanks!
推荐答案
正如帕维尔要求,这里是code:
As requested by Pawel, here is the code:
public class AjaxGetAttribute : ActionMethodSelectorAttribute
{
public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo)
{
var isHttpGet = new AcceptVerbsAttribute(HttpVerbs.Get).IsValidForRequest(controllerContext, methodInfo);
return isHttpGet && controllerContext.HttpContext.Request.IsAjaxRequest();
}
}
public class AjaxPostAttribute : ActionMethodSelectorAttribute
{
public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo)
{
var isHttpPost = new AcceptVerbsAttribute(HttpVerbs.Post).IsValidForRequest(controllerContext, methodInfo);
return isHttpPost && controllerContext.HttpContext.Request.IsAjaxRequest();
}
}
这篇关于MVC3:ActionMethodSelectorAttribute时导致HttpPostAttribute被忽略的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!