by Greg
13. December 2010 21:57
Here's a little class I just put together to enable you to add HTTP Headers to a View in ASP.NET MVC 3.
It's pretty simple and I might quite easily have missed something very similar that is built in.
I do however like the idea of using an attribute for this rather than having a bunch of AppendHeader calls in the body of the Controller Action.
///
/// Represents an attribute that is used to add HTTP Headers to a Controller Action response.
///
public class HttpHeaderAttribute : ActionFilterAttribute
{
///
/// Gets or sets the name of the HTTP Header.
///
/// The name.
public string Name { get; set; }
///
/// Gets or sets the value of the HTTP Header.
///
/// The value.
public string Value { get; set; }
///
/// Initializes a new instance of the class.
///
/// The name.
/// The value.
public HttpHeaderAttribute(string name, string value)
{
Name = name;
Value = value;
}
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
filterContext.HttpContext.Response.AppendHeader(Name, Value);
base.OnResultExecuted(filterContext);
}
}
You then use it like this:
[HttpHeader("X-Robots-Tag", "noindex")]
public ActionResult Edit(int id)
{
// ...
}