13

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.

user70192
  • 13,786
  • 51
  • 160
  • 240

2 Answers2

31
    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)
    {
        // ...
    }
Raab
  • 34,778
  • 4
  • 50
  • 65
25
Response.AppendHeader("Access-Control-Allow-Origin", "*");
HABO
  • 15,314
  • 5
  • 39
  • 57
  • I got another problem: when Browser perform next request. it does not not include the header "Access-Control-Allow-Origin" back to server. How to make browser return all headers from its prior response. – Tola Ch. Dec 18 '15 at 00:32
  • @TolaCh. AFAIK there is no reason that a browser should return all response headers in subsequent requests. You could use JavaScript [getAllResponseHeaders](http://help.dottoro.com/ljnxxhwv.php) and [setRequestHeader](http://help.dottoro.com/ljhcrlbv.php) to propagate the headers from a response to a request. – HABO Dec 18 '15 at 02:30