一个方法MVC设置访问级别从阿贾克斯称为 [英] MVC Set accessibility level on a method called from ajax

查看:87
本文介绍了一个方法MVC设置访问级别从阿贾克斯称为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想保护我的公共方法由用户被调用。

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

由于我打电话从AJAX脚本中的动作,我不能使用任何访问修饰符(私有,保护等)。

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

此外,[HttpPost]不从做一个假的请求停止用户。

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

任何人都得到一个解决方案?

Anyone got a solution?

感谢

推荐答案

创建一个动作过滤器,即可以通过AJAX调用的操作方法仅

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()
{
  ....

这篇关于一个方法MVC设置访问级别从阿贾克斯称为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆