MVC Set accessibility level on a method called from ajax

最后都变了- 提交于 2019-11-26 14:50:01

问题


I would like to protect my public method from being called by a user.

Because I'm calling the action from an ajax script I can't use any access modifiers, (private, protected etc).

Also, [HttpPost] doesn't stop the user from doing a fake request.

Anyone got a solution?

Thanks


回答1:


Create an action filter that allows action methods to be called by AJAX only

namespace MyFilters
{
  [AttributeUsage(AttributeTargets.Method)]
  public class AjaxOnlyAttribute : ActionFilterAttribute
  {
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
      if (!filterContext.HttpContext.Request.IsAjaxRequest())
      {
        filterContext.HttpContext.Response.StatusCode = 404;
        filterContext.Result = new HttpNotFoundResult();
      }
      else
      {
        base.OnActionExecuting(filterContext);
      }
    }
  }
}

Then apply this to the action method

[AjaxOnly]
public JsonResult DoSomething()
{
  ....


来源:https://stackoverflow.com/questions/23900411/mvc-set-accessibility-level-on-a-method-called-from-ajax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!