问题
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