Why is JsonRequestBehavior needed?

后端 未结 5 1212
[愿得一人]
[愿得一人] 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条回答
  •  萌比男神i
    2020-11-22 05:58

    To make it easier for yourself you could also create an actionfilterattribute

    public class AllowJsonGetAttribute : ActionFilterAttribute
    {
        public override void OnResultExecuting(ResultExecutingContext filterContext)
        {
            var jsonResult = filterContext.Result as JsonResult;
    
            if (jsonResult == null)
                throw new ArgumentException("Action does not return a JsonResult, 
                                                       attribute AllowJsonGet is not allowed");
    
            jsonResult.JsonRequestBehavior = JsonRequestBehavior.AllowGet;            
    
            base.OnResultExecuting(filterContext);
        }
    }
    

    and use it on your action

    [AllowJsonGet]
    public JsonResult MyAjaxAction()
    {
        return Json("this is my test");
    }
    

提交回复
热议问题