If I wanted to use attributes to muck about with an MVC return contentType, would it be better to do it in OnResultExecuting or OnResultExecuted?

Deadly 提交于 2020-01-15 10:09:57

问题


In the pursuit of solving an absurd problem, I need to append a value to my querystring (did that in javascript) and test if it exists on the server (because this may come from ajax or an iframe, so there's no header potential, sadly, and I'm trying to avoid adding a value to my <form> element). To that end, I've devised this little snippet, and I'm not sure where to put the "setter" block:

using System.Web.Mvc;

namespace Company.Client.Framework.Mvc
{
  class CreateFormDialogResponseAttribute : ActionFilterAttribute
  {
    private bool SetContentType { get; set; }

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        SetContentType = !filterContext.HttpContext.Request.Params["FormDialogRequest"].IsEmpty();

        base.OnActionExecuting(filterContext);
    }
    public override void OnResultExecuting(ResultExecutingContext filterContext)
    { 
        //do I set it here? (A)
        if (SetContentType)
            filterContext.HttpContext.Response.ContentType = "text/json";
        base.OnResultExecuting(filterContext);
    }
    public override void OnResultExecuted(ResultExecutedContext filterContext)
    {
        //do I set it here? (B)
        if (SetContentType)
            filterContext.HttpContext.Response.ContentType = "text/json";
        base.OnResultExecuted(filterContext);
    }
  }
}

If I set it at (A) then it seems like the client still has time to "override" the attribute, if need be. Whereas (B) looks like the "I don't care what you think you want to do" position. Is that an accurate understanding?


回答1:


self-answer:

Because I need to override the value set by the ActionResult itself, I have to come in after the method as already done it's work. Because I want to avoid the situation where the developer has manually set the type, I'm doing two checks, one to see if we should set it, and one to see if it's "application/json" (the default).



来源:https://stackoverflow.com/questions/14130822/if-i-wanted-to-use-attributes-to-muck-about-with-an-mvc-return-contenttype-woul

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!