我已经被困了2天了。
有人可以提供一个如何为WCF服务执行跨域AJAX帖子的示例吗?
我正在尝试将图像上传到WCF服务器。
修改
WCF服务:
[WebInvoke(UriTemplate = "/upload", Method = "POST", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped), CorsEnabled]
void UploadImage(Stream image);
Ajax Call:
function UploadImage() {
image = document.getElementById("myimage").src;
var data = '{"image": "' + image + '"}'
//alert(data);
$.ajax({
url: "http://localhost:44665/api/upload",
type: "POST",
contentType: "application/json",
data: data,
success: function (result) {
alert("success");
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR.responseText);
}
});
}
如果我将WCF参数从Stream更改为string,我可以使用它。但我需要上传图片而不是字符串。
我现在收到的WCF错误是:
The server encountered an error processing the request. See server logs for more details.
**编辑2 ** 我添加了以下答案中提到的global.asax代码,并将其添加到我的web.config:
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="myServiceBehavior">
<servicedebug includeexceptiondetailinfaults="true" />
</behavior>
<behavior name="">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true"
aspNetCompatibilityEnabled="true"/>
</system.serviceModel>
</configuration>
我现在在Google Chrome控制台中收到错误消息:
POST http://localhost:44665/api/upload 500 (Internal Server Error)
答案 0 :(得分:5)
因此,您尝试从JavaScript到另一个域中托管的WCF服务进行POST操作。通常,如果不在WCF服务端执行某些特殊设置,则无法执行此操作。
您必须将以下标头添加到服务端Global.asax.cs
的响应中(如果服务项目不包含Global.asax.cs
创建一个)。
protected void Application_BeginRequest(object sender, EventArgs e)
{
//..
EnableCrossDomainCall();
}
private void EnableCrossDomainCall()
{
// this header tells that from any domain you can access me.
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
// this one tells about the supported methods to client.
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods",
"GET, POST, 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();
}
}
<强>更新强>
你不能只通过AJAX发布任何文件,通过AJAX你只能传输数据。您可以使用隐藏iframe的this插件上传模仿AJAX的文件。
您可以像在此link中那样处理WCF端的流对象。首先尝试上传小尺寸图片,然后通过在web.config中设置maxRequestLength来控制最大尺寸。
答案 1 :(得分:0)
我遇到了这个问题并尝试了代码无效。
我更改了代码并开始工作。
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();
}