Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change default ASP MVC Request Header to add your own values

Im trying to change all my ASP MVC HTTP response headers to have another value by default for implementing Pingback auto-discovery in my blog application.

The default header (on Cassini) is :

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

and i want an extra value added :

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

I have googled a bit and found a neet solution : -- to derive from ActionFilterAttribute and override the OnResultExecuted method:

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);
        }

    }

And then simply i put the attribute on my Controllers methods:

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

When i runt the app i get the following error : enter image description here

Any ideas?

like image 953
Alex Peta Avatar asked Apr 20 '12 22:04

Alex Peta


People also ask

Can I add custom header to HTTP request?

In the Home pane, double-click HTTP Response Headers. In the HTTP Response Headers pane, click Add... in the Actions pane. In the Add Custom HTTP Response Header dialog box, set the name and value for your custom header, and then click OK.

What are custom headers in API?

Custom Headers allow us to add extra content to our HTTP requests and responses, which we can pass between the client and server. We can use custom headers for metadata, such as defining the current version of the API that is being used.


1 Answers

I know this post is old...but wanted to point out that while OnResultExecuting is the proper method to be doing this from, the original post shows that he was trying to add headers to the request. One does not simply add headers to a request and expect them to show up in the response. ;-)

Also, the proper way to add headers to a response...that also works in Cassini...is to use the following:

filterContext.HttpContext.Response.AddHeader("X-My-Request-Header", "works in cassini");
like image 118
Joe the Coder Avatar answered Sep 20 '22 18:09

Joe the Coder