Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding headers in ASP.NET MVC 3

I have a basic ASP.NET MVC 3 app. I have a basic action that looks like the following:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddItem(string id, string name, string description, string username)
{
  // Do stuff
  return Json(new { statusCode = 1 });
}

I am trying to let someone access this action via a JQuery Mobile app that will be hosted in Phone Gap. I was told that I need to return Access-Control-Allow-Origin: * in my header. However, I'm not sure how to return that in the header. Can someone please show me how to do that?

Thank you so much.

like image 406
user70192 Avatar asked May 26 '12 11:05

user70192


People also ask

How to add header in ASP net?

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 is HTTP headers in MVC?

The HTTP headers help protect against some of the attacks which can be executed against a website. securityheaders.io is used to test and validate the HTTP headers as well as F12 in the browser. NWebSec is used to add most of the HTTP headers which improve security for the MVC application.

How do I add a response header?

Select the web site where you want to add the custom HTTP response header. In the web site pane, double-click HTTP Response Headers in the IIS section. In the actions pane, select Add. In the Name box, type the custom HTTP header name.


1 Answers

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

[HttpHeader("Access-Control-Allow-Origin","*")]
    public ActionResult myaction(int id)
    {
        // ...
    }
like image 187
Raab Avatar answered Nov 13 '22 05:11

Raab