C# 使用XML格式的WCF服务
我有一个MediaServiceLoop.svc文件,它有一个函数GetMediaLoops,如下所示C# 使用XML格式的WCF服务,c#,angularjs,asp.net-mvc,wcf,cors,C#,Angularjs,Asp.net Mvc,Wcf,Cors,我有一个MediaServiceLoop.svc文件,它有一个函数GetMediaLoops,如下所示 [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Xml)] public string GetMediaLoops() { string strFileName
[WebInvoke(Method = "POST",
BodyStyle = WebMessageBodyStyle.Wrapped,
ResponseFormat = WebMessageFormat.Xml)]
public string GetMediaLoops()
{
string strFileName = "GetMediaLoops_response.xml";
string strResult = GetFileData(strFileName);
return strResult;
}`
代码的角度是这样的`
mainApp.factory('MediaService', ['$http', function ($http) {
var factory = {};
factory.getMediaLoops = function () {
return $http.post("http://localhost:62467/MediaLoopService.MediaLoop.svc/GetMediaLoops");
}
return factory;}]);
控制器代码:
MediaService.getMediaLoops()
.then(function (response) {
$scope.media = response.data;
}, function (error) {
$scope.status = 'Unable to load customer data: ' + error.message;
});
`
我能够在Postman和Chrome Network()中获得响应,但是我确实收到错误“请求的资源上不存在“Access Control Allow Origin”头。因此不允许访问Origin“”。并且代码流跳过getMediaLoops调用中的响应和错误块
我还为上面的错误在Global.asax文件中添加了以下代码,但仍然得到上面的错误,如有任何帮助,将不胜感激
protected void Application_BeginRequest(object sender, EventArgs e)
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "http://localhost");
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "POST, PUT, DELETE");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
HttpContext.Current.Response.End();
}
}
尝试在web.config中为服务添加以下配置:
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
<modules runAllManagedModulesForAllRequests="true"/>
<directoryBrowse enabled="true"/>
</system.webServer>
尽管当在API中不传递任何参数时,上述答案工作正常,但对于传递数据,WCF未能作为浏览器创建的飞行前请求的一部分响应选项请求,并抛出错误“方法不允许:405”,因此,永久性的解决方案是在服务项目中创建一个全局文件,检查选项请求并相应地添加标题
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, PUT, DELETE");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
HttpContext.Current.Response.End();
}
}
}