Why is JsonRequestBehavior needed?

后端 未结 5 1141
[愿得一人]
[愿得一人] 2020-11-22 05:27

Why is Json Request Behavior needed?

If I want to restrict the HttpGet requests to my action I can decorate the action with the [Http

5条回答
  •  花落未央
    2020-11-22 06:07

    Improving upon the answer of @Arjen de Mooij a bit by making the AllowJsonGetAttribute applicable to mvc-controllers (not just individual action-methods):

    using System.Web.Mvc;
    public sealed class AllowJsonGetAttribute : ActionFilterAttribute, IActionFilter
    {
        void IActionFilter.OnActionExecuted(ActionExecutedContext context)
        {
            var jsonResult = context.Result as JsonResult;
            if (jsonResult == null) return;
    
            jsonResult.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
        }
    
        public override void OnResultExecuting(ResultExecutingContext filterContext)
        {
            var jsonResult = filterContext.Result as JsonResult;
            if (jsonResult == null) return;
    
            jsonResult.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
            base.OnResultExecuting(filterContext);
        }
    }
    

提交回复
热议问题