If I wanted to use attributes to muck about with a

2019-08-03 18:25发布

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条回答
别忘想泡老子
2楼-- · 2019-08-03 18:49

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).

查看更多
登录 后发表回答