以 XML 格式使用 Angular 的 WCF 服务
Posted
技术标签:
【中文标题】以 XML 格式使用 Angular 的 WCF 服务【英文标题】:Consuming WCF service in angular in XML format 【发布时间】:2018-04-20 20:32:32 【问题描述】:我有一个 MediaServiceLoop.svc 文件,它有一个 GetMediaLoops 函数,看起来像这样 `
[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;]);
Controller code:
MediaService.getMediaLoops()
.then(function (response)
$scope.media = response.data;
, function (error)
$scope.status = 'Unable to load customer data: ' + error.message;
);
`
我能够在 Postman 和 Chrome 网络 () 中获得响应,但是我确实收到“请求的资源上不存在‘Access-Control-Allow-Origin’标头的错误。来源’ http://localhost:2206' 因此不允许访问。”并且代码流会跳过 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();
【问题讨论】:
【参考方案1】:虽然在 API 中不传递任何参数时上述答案工作正常,但对于传递数据,WCF 未能响应 OPTIONS 请求作为浏览器创建的预检请求的一部分并抛出错误“方法不允许:405”,因此永久的解决方案是在服务项目中创建一个全局文件并检查 OPTIONS 请求并相应地添加标题
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();
【讨论】:
【参考方案2】:尝试在web.config中为服务添加如下配置:
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
<modules runAllManagedModulesForAllRequests="true"/>
<directoryBrowse enabled="true"/>
</system.webServer>
【讨论】:
以上是关于以 XML 格式使用 Angular 的 WCF 服务的主要内容,如果未能解决你的问题,请参考以下文章
从 wcf RESTful 响应中的 xml 中删除 xmlns 属性
WCF 错误:期待状态“元素”。遇到名称为“文本”、名称空间“”的 XML 格式的 post call