How to add cross domain support to WCF service

后端 未结 4 830
暖寄归人
暖寄归人 2020-11-30 07:07

I\'m trying to allow POST requests from my javascript app hosted at localhost:80 to a WCF REStful service hosted at a different port, but somehow it doesn\'t work. I\'ve tri

4条回答
  •  粉色の甜心
    2020-11-30 07:19

    This worked better for me than the Web.config version:

    Create a Global.asax

    Add this method to the Global.asax.cs:

    using System.Web;
    
    namespace StackOverflow
    {
        public class Global : System.Web.HttpApplication
        {
            protected void Application_BeginRequest(object sender, EventArgs e)
            {
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
                if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
                {
                    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
                    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
                    HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
                    HttpContext.Current.Response.End();
                }
            }
        }
    }
    

    Ref: http://www.dotnet-tricks.com/Tutorial/wcf/X8QN260412-Calling-Cross-Domain-WCF-Service-using-Jquery.html

提交回复
热议问题