• ActionMethodSelectorAttribute的使用


    • 判断Controller请求是否来自Ajax

    [HttpGet]
            [AjaxOnly]
            public ActionResult GetList()
            {
                var data = dTImgIBLL.GetList();
                return JsonResult(data);
            }
    

      

    AjaxOnlyAttribute的定义如下:
    [AttributeUsage(AttributeTargets.Method)]
        public class AjaxOnlyAttribute : ActionMethodSelectorAttribute
        {
            /// <summary>
            /// 初始化仅允许Ajax操作
            /// </summary>
            /// <param name="ignore">跳过Ajax检测</param>
            public AjaxOnlyAttribute(bool ignore = false)
            {
                Ignore = ignore;
            }
    
            /// <summary>
            /// 跳过Ajax检测
            /// </summary>
            public bool Ignore { get; set; }
    
            /// <summary>
            /// 验证请求有效性
            /// </summary>
            /// <param name="controllerContext">控制器上下文</param>
            /// <param name="methodInfo">方法</param>
            public override bool IsValidForRequest(ControllerContext controllerContext, System.Reflection.MethodInfo methodInfo)
            {
                if (Ignore)
                    return true;
                return controllerContext.RequestContext.HttpContext.Request.IsAjaxRequest();
            }
        }
    

      

    • 检查Post数据的“名称”。如果Post的表单有一个名为“cancelorder”的名称-值对,则将执行Action方法

    • Nopcommerce项目:srcPresentationNop.Web.FrameworkControllersFormValueRequiredAttribute.cs
    [HttpPost]
            [FormValueRequired("save")]
            public virtual IActionResult ProductAddPopup(AddProductToCategoryModel model)
            {
                if (!_permissionService.Authorize(StandardPermissionProvider.ManageCategories))
                    return AccessDeniedView();
    
                //get selected products
                var selectedProducts = _productService.GetProductsByIds(model.SelectedProductIds.ToArray());
                if (selectedProducts.Any())
                {
                    var existingProductCategories = _categoryService.GetProductCategoriesByCategoryId(model.CategoryId, showHidden: true);
                    foreach (var product in selectedProducts)
                    {
                        //whether product category with such parameters already exists
                        if (_categoryService.FindProductCategory(existingProductCategories, product.Id, model.CategoryId) != null)
                            continue;
    
                        //insert the new product category mapping
                        _categoryService.InsertProductCategory(new ProductCategory
                        {
                            CategoryId = model.CategoryId,
                            ProductId = product.Id,
                            IsFeaturedProduct = false,
                            DisplayOrder = 1
                        });
                    }
                }
    
                ViewBag.RefreshPage = true;
    
                return View(new AddProductToCategorySearchModel());
            }
    

      

    public override bool IsValidForRequest(RouteContext routeContext, ActionDescriptor action)
            {
                if (routeContext.HttpContext.Request.Method != WebRequestMethods.Http.Post)
                    return false;
    
                foreach (var buttonName in _submitButtonNames)
                {
                    try
                    {
                        switch (_requirement)
                        {
                            case FormValueRequirement.Equal:
                                {
                                    if (_validateNameOnly)
                                    {
                                        //"name" only
                                        if (routeContext.HttpContext.Request.Form.Keys.Any(x => x.Equals(buttonName, StringComparison.InvariantCultureIgnoreCase)))
                                            return true;
                                    }
                                    else
                                    {
                                        //validate "value"
                                        //do not iterate because "Invalid request" exception can be thrown
                                        string value = routeContext.HttpContext.Request.Form[buttonName];
                                        if (!string.IsNullOrEmpty(value))
                                            return true;
                                    }
                                }
                                break;
                            case FormValueRequirement.StartsWith:
                                {
                                    if (_validateNameOnly)
                                    {
                                        //"name" only
                                        if (routeContext.HttpContext.Request.Form.Keys.Any(x => x.StartsWith(buttonName, StringComparison.InvariantCultureIgnoreCase)))
                                            return true;
                                    }
                                    else
                                    {
                                        //validate "value"
                                        foreach (var formValue in routeContext.HttpContext.Request.Form.Keys)
                                            if (formValue.StartsWith(buttonName, StringComparison.InvariantCultureIgnoreCase))
                                            { 
                                                var value = routeContext.HttpContext.Request.Form[formValue];
                                                if (!string.IsNullOrEmpty(value))
                                                    return true;
                                            }
                                    }
                                }
                                break;
                        }
                    }
                    catch (Exception exc)
                    {
                        //try-catch to ensure that no exception is throw
                        Debug.WriteLine(exc.Message);
                    }
                }
                return false;
            }
    

      

    以下其他功能,还没有研究,有待补充:

    1、控制Action,实现不同角色同一Action跳转到不同View

    2、限制Action的提交方式,实现同一Action接受不同的或两种以上的提交方式(同时接受Post、Put等)

    3、实现同一form多个submit动作,提交到不同的Action

  • 相关阅读:
    [PY3]——heap模块 和 堆排序
    [PY3]——求TopN/BtmN 和 排序问题的解决
    [转载+补充][PY3]——环境配置(2)——windows下安装pycharm并连接Linux的python环境
    [转载+补充]windows下SVN客户端的安装
    [Visual studio code 常见问题解决] ——中文乱码、
    Smrty模版总结(转)
    cms内容模型标签
    phpcms图文总结(转)
    phpcms总结(转)
    PHP总结
  • 原文地址:https://www.cnblogs.com/gougou1981/p/12311078.html
Copyright © 2020-2023  润新知