在ASP.NET MVC 3中添加标头

时间:2012-05-26 11:11:09

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

我有一个基本的ASP.NET MVC 3应用程序。我的基本操作如下所示:

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

我试图通过将在Phone Gap中托管的JQuery Mobile应用程序让某人访问此操作。有人告诉我,我需要在标题中返回Access-Control-Allow-Origin: *。但是,我不知道如何在标题中返回它。有人可以告诉我该怎么做吗?

非常感谢你。

2 个答案:

答案 0 :(得分:30)

    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)
    {
        // ...
    }

答案 1 :(得分:25)

Response.AppendHeader("Access-Control-Allow-Origin", "*");