从AJAx向WCF Webservice链接发送数据

本文关键字:接发 数据 链接 Webservice AJAx WCF | 更新日期: 2023-09-27 18:07:45

希望将数据从Ajax发送到包含GetQuickQuote(字符串x)方法的Wcf服务,并从Webservice返回数据。

Jquery

 $('#txtBox').blur(function () {
        debugger;
        $.ajax({
            type: "POST",
            url: "http://logicalfire-pc:8090/Libertytest.Service1.svc" + "/GetQuickQuote", 
            crossDomain: true,
            data: JSON.stringify({ x: 'ght'}),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
                if (response.d == true) {
                    alert("You will now be redirected.");
                }
            },
            error:function(eror)
            {
                alert('failure');
            }
        })
    });

WCF服务包含

public string GetQuickQuote(string x)
        {
            var ReadXmlPath = GetApplicationPath() + "TextFile1.txt";
x=ReadXmlPath;
    return x;

       }

我得到以下响应:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://logicalfire-pc:8090/Libertytest.Service1.svc/GetQuickQuote. (Reason: CORS header 'Access-Control-Allow-Origin' missing).

从AJAx向WCF Webservice链接发送数据

在webservice的global.asax文件中添加以下代码

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();
   }
}