问题描述
为了解决一个荒谬的问题,我需要在查询字符串中附加一个值(在javascript中进行了验证)并测试它是否在服务器上存在(因为这可能来自ajax或iframe,因此没有标头)可悲的是,我试图避免在< form>
元素中添加一个值)。为此,我设计了这个小片段,但不确定在哪里放置 setter块:
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);
}
}
}
如果我将其设置为(A)
然后,如果需要,客户端似乎仍有时间覆盖该属性。而(B)
看起来像我不在乎您想做什么 位置。
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?
推荐答案
自我解答:
因为我需要覆盖ActionResult本身设置的值,所以我必须在方法已经完成后进入。因为我想避免开发人员手动设置类型的情况,所以我要进行两项检查,一项是查看是否应该设置它,另一项是查看它是否是 application / json(默认值)。
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).
这篇关于如果我想使用属性与MVC返回contentType混为一谈,最好在OnResultExecuting或OnResultExecuted中进行操作吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!