从Web Api获取XML到Angular
各位StackOverflow用户好 我想获取来自web api Asp.net核心的字符串 这是我的控制器的代码:从Web Api获取XML到Angular,angular,asp.net-core,asp.net-web-api2,angular7,asp.net-core-webapi,Angular,Asp.net Core,Asp.net Web Api2,Angular7,Asp.net Core Webapi,各位StackOverflow用户好 我想获取来自web api Asp.net核心的字符串 这是我的控制器的代码: [HttpPost("Xml")] public string Xml() { try { using (StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8))
[HttpPost("Xml")]
public string Xml()
{
try
{
using (StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8))
{
return _xmlBeautifier.Beautify(reader.ReadToEnd());
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace);
throw ex;
}
}
这是我的角度代码:
onSubmit() {
const httpOptions = {
headers: new HttpHeaders({
'Accept': 'text/xml',
'Content-Type': 'text/xml'
})
};
this.http.post('http://localhost:5000/api/xml/xml', this.xmlForm.controls['XmlData'].value, httpOptions)
.subscribe(res => {
alert('SUCCESS !!');
})
}
我现在要做的是检查是否正确获取了XML字符串。我还没有打印已解析XML的代码,但我已经有了错误
SyntaxError:JSON.parse位置0处的JSON中出现意外标记<
如何修复错误?我已经使用Postman测试了API,它工作正常
请看下面的截图
更新:
以下是完整的错误消息:
HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK", url: "http://localhost:5000/api/xml/xml", ok: false, …
message: "Unexpected token < in JSON at position 0"
stack: "SyntaxError: Unexpected token < in JSON at position 0↵ at JSON.parse (<anonymous>)↵ at XMLHttpRequest.onLoad (http://localhost:4200/vendor.js:19139:51)↵ at ZoneDelegate.invokeTask (http://localhost:4200/poly
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
message: "Http failure during parsing for http://localhost:5000/api/xml/xml"
name: "HttpErrorResponse"
ok: false
status: 200
statusText: "OK"
url: "http://localhost:5000/api/xml/xml"
我还使用了来自的纸质仪表板角度模板
更新:
我上传了示例web api和我正在使用的示例angular代码
HttpClient的响应类型的默认值是JSON。如果要请求非JSON数据,只需将标头设置为以下值:
this.http.get('...', { responseType: 'text' });
responseType?: 'arraybuffer' | 'blob' | 'json' | 'text'
对你来说,应该是这样
onSubmit() {
this.http.post('http://localhost:5000/api/xml/xml', { responseType: 'text' })
.subscribe(res => {
alert('SUCCESS !!');
});
}
很好的一天。我仍然收到这个错误。我所做的是为onSubmit粘贴代码,但错误仍然存在。我更新了问题并粘贴了完整的错误,以防遗漏重要的细节。谢谢我创建了一个示例问题来尝试您的解决方案,并且我能够使用上面的代码调用API我编辑了上面的注释。否则,你能在GitHub中发布你的代码让我在我的电脑上试用吗?你好,祝你好运。我更新了问题。我上传了web api和angular代码。到现在为止,我尝试了你提供的解决方案,但仍然没有成功。它还不起作用。非常感谢您的时间和帮助,我们刚刚更新了解决方案。您只需要使用一个带有responseType:text的对象来传递到post选项。如果使用HttpHeader,则会出现错误。它正在工作。非常感谢您抽出时间。Stackoverflow成员是最好的。