在ASP.NET MVC 3中添加头信息

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: *。但是,我不确定如何在头文件中返回它。请问有人可以向我展示如何做到这一点吗?

非常感谢。

2个回答

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

当前链接:http://blog.gregbrant.com/post/Adding-Custom-HTTP-Headers-to-an-ASPNET-MVC-Response - Phillip Copley

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

我又遇到了一个问题: 当浏览器执行下一个请求时,它没有将头部"Access-Control-Allow-Origin"返回给服务器。 如何让浏览器返回其先前响应中的所有头部。 - Tola Ch.
@TolaCh。据我所知,浏览器没有理由在后续请求中返回所有响应头。您可以使用JavaScript的getAllResponseHeaderssetRequestHeader将响应头从响应传播到请求。 - HABO

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接