更改默认的ASP MVC请求标头以添加您自己的值

时间:2012-04-20 22:56:01

标签: c# asp.net-mvc http-headers

我试图将我的所有ASP MVC HTTP响应标头更改为默认情况下另一个值,以便在我的博客应用程序中实现Pingback自动发现。

默认标头(在Cassini上)是:

Cache-Control   private
Connection  Close
Content-Length  20901
Content-Type    text/html; charset=utf-8
Date    Fri, 20 Apr 2012 22:46:11 GMT
Server  ASP.NET Development Server/10.0.0.0
X-AspNet-Version    4.0.30319
X-AspNetMvc-Version 3.0

我希望增加一个额外的值:

X-Pingback: http://localhost:4912/pingback/xmlrpcserver

我已经google了一下,找到了一个neet解决方案: - 从 ActionFilterAttribute 派生并覆盖 OnResultExecuted 方法:

public class HttpHeaderAttribute : ActionFilterAttribute
    {

        public string Name { get; set; }
        public string Value { get; set; }

        public HttpHeaderAttribute(string name, string value)
        {
            Name = name;
            Value = value;
        }

        public override void OnResultExecuted(ResultExecutedContext filterContext)
        {
            filterContext.HttpContext.Request.Headers.Add(Name, Value);
            base.OnResultExecuted(filterContext);
        }

    }

然后我将该属性放在我的Controllers方法上:

[HttpHeader("X-Pingback","http://localhost:4912/pingback/xmlrpcserver")]
        public ActionResult Index()
        {
            var allArticles = _repository.GetPublishedArticles(SortOrder.desc);
            return View(allArticles);
        }

当我破坏应用程序时,我收到以下错误: enter image description here

有什么想法吗?

3 个答案:

答案 0 :(得分:5)

我知道这篇文章很老了...但是想指出虽然OnResultExecuting是正确的方法,但原始帖子显示他正在尝试向请求添加标题。一个不是简单地向请求添加标头并期望它们出现在响应中。 ; - )

此外,将标题添加到响应中的正确方法......也适用于Cassini ...是使用以下内容:

filterContext.HttpContext.Response.AddHeader("X-My-Request-Header", "works in cassini");

答案 1 :(得分:3)

我认为您的问题可能只是因为您在OnResultExecuted中执行此操作,因此您尝试修改标题的时间太晚了。请尝试覆盖OnResultExecuting

http://msdn.microsoft.com/en-us/library/system.web.mvc.actionfilterattribute.onresultexecuting.aspx

答案 2 :(得分:1)

这可能会也可能不会起作用(显然,如果不是,我会删除未来用户的答案)。听起来像异常Operation is not supported by this platform,Cassini很多人不支持自定义标题(这可能很奇怪,但有可能)。我建议的是确保您使用Visual Studio 2010 SP1,然后安装IIS Express(这是对Cassini的升级,更像是真正的IIS),然后切换您的项目以使用IIS Express和看看你是否得到了同样的例外。

Switching from Cassini to IIS Express

此外,您可能希望查看Why does HttpCacheability.Private suppress ETags?,因为它也可能为您提供替代解决方案。