ASP.NET MVC 2.0 JsonRequestBehavior Global Setting

前端 未结 6 978
轻奢々
轻奢々 2021-02-02 06:50

ASP.NET MVC 2.0 will now, by default, throw an exception when an action attempts to return JSON in response to a GET request. I know this can be overridden on a method by method

6条回答
  •  眼角桃花
    2021-02-02 07:45

    There's another option. Use Action Filters.

    Create a new ActionFilterAttribute, apply it to your controller or a specific action (depending on your needs). This should suffice:

    public class JsonRequestBehaviorAttribute : ActionFilterAttribute
    {
        private JsonRequestBehavior Behavior { get; set; }
    
        public JsonRequestBehaviorAttribute()
        {
            Behavior = JsonRequestBehavior.AllowGet;
        }
    
        public override void OnResultExecuting(ResultExecutingContext filterContext)
        {
            var result = filterContext.Result as JsonResult;
    
            if (result != null)
            {
                result.JsonRequestBehavior = Behavior;
            }
        }
    }
    

    Then apply it like this:

    [JsonRequestBehavior]
    public class Upload2Controller : Controller
    

提交回复
热议问题