我有一个 WCF 服务,装饰有 WebInvoke 属性和用于启用 JSON 的 WebHttp 绑定。在我们尝试使其跨域工作之前,可以从 JavaScript 访问该服务。你能推荐一下如何让它跨域工作吗?
我们尝试创建代理 Web 处理程序,但每次 WebHttpRequest 尝试访问它时它都会给出“错误请求”。
我有一个 WCF 服务,装饰有 WebInvoke 属性和用于启用 JSON 的 WebHttp 绑定。在我们尝试使其跨域工作之前,可以从 JavaScript 访问该服务。你能推荐一下如何让它跨域工作吗?
我们尝试创建代理 Web 处理程序,但每次 WebHttpRequest 尝试访问它时它都会给出“错误请求”。
我必须做的是创建一个代理。跨域请求仅适用于 GET 动词,不适用于 POST。我所有的请求都通过代理,如果它是一个 POST,那么它就像一个典型的代理。如果请求使用的是 GET,那么我必须将其转换为 POST。(我在我的服务合同中将 POST 指定为动词)。
在客户端,我使用 JQuery 的 josnp(带填充的 json)功能将正确的信息附加到查询字符串中。
private static readonly Properties.Settings settings = new Properties.Settings();
public void ProcessRequest(HttpContext context)
{
try
{
string wcfAddress = context.Request.QueryString["WcfAddress"];
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(settings.WCFAddress + wcfAddress);
request.ContentType = "application/json";
request.Method = "POST";
if (context.Request.RequestType == "GET")
{
string callback = context.Request.QueryString["callback"];
string qs = context.Request.QueryString[null];
byte[] body = body = Encoding.UTF8.GetBytes(qs);
request.ContentLength = body.Length;
request.GetRequestStream().Write(body, 0, body.Length);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
{
string contents = reader.ReadToEnd();
contents = callback + "(" + contents + ");";
context.Response.ContentType = "application/json";
context.Response.Write(contents);
response.Close();
reader.Close();
}
}
else if (context.Request.RequestType == "POST")
{
byte[] body = new byte[context.Request.ContentLength];
context.Request.InputStream.Read(body, 0, body.Length);
request.ContentLength = body.Length;
request.GetRequestStream().Write(body, 0, body.Length);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
{
string contents = reader.ReadToEnd();
context.Response.ContentType = "application/json";
context.Response.Write(contents);
response.Close();
reader.Close();
}
}
}
catch (Exception ex)
{
System.Diagnostics.Trace.WriteLine(ex.ToString());
}
}
按照这个优秀文章系列的第 1-4 部分中提供的步骤,您最终会得到一个干净的解决方案。我在生产中使用它没有任何问题。
您必须进行一项调整以使其适用于所有浏览器。在CorsDispatchMessageInspector.BeforeSendReply
评论中检查:
如果(状态。消息!= null)
否则,“允许”标头仅适用于飞行前请求,而不适用于实际请求。
要解决问题,请执行以下操作
创建一个 Global.asax 并添加以下代码以启用 Ajax 跨域 POST
public void Application_BeginRequest(object sender, EventArgs e)
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST,OPTIONS");
if ((HttpContext.Current.Request.HttpMethod == "OPTIONS"))
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
HttpContext.Current.Response.End();
}
}
}