MVC Set accessibility level on a method called from ajax

后端 未结 1 329
情话喂你
情话喂你 2020-12-02 01:18

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

相关标签:
1条回答
  • 2020-12-02 02:07

    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()
    {
      ....
    
    0 讨论(0)
提交回复
热议问题