13

我有一个基本的 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: *在我的标题中返回。但是,我不确定如何在标题中返回它。有人可以告诉我该怎么做吗?

非常感谢。

4

2 回答 2

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)
    {
        // ...
    }
于 2012-05-26T11:47:35.400 回答
25
Response.AppendHeader("Access-Control-Allow-Origin", "*");
于 2012-05-26T11:17:14.550 回答