【发布时间】:2012-06-11 17:40:27
【问题描述】:
我在这个问题上被困了 2 天。
谁能提供一个如何将跨域 AJAX 发布到 WCF 服务的示例?
我正在尝试将图像上传到 WCF 服务器。
编辑
WCF 服务:
[WebInvoke(UriTemplate = "/upload", Method = "POST", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped), CorsEnabled]
void UploadImage(Stream image);
Ajax 调用:
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 更改为字符串,我可以让它工作。但我需要上传图片而不是字符串。
我现在收到一个 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)
【问题讨论】:
-
我的问题与上传图片有关。我能够让 ajax 帖子与字符串一起正常工作。但是,一旦我将 Stream 类型的参数添加到我的服务中,客户端将无法连接,并且客户端上出现以下错误:Access-Control-Allow-Origin 不允许 Origin localhost:44810。
-
我不知道您是如何通过 ajax 上传图像的,但我已经发布了解决 CORS 问题的答案。
标签: ajax wcf cross-domain