首页 > 解决方案 > 从 Web Api 获取 XML 到 Angular

问题描述

嗨,StackOverflow 用户。

我想获取来自 web api (Asp.net Core) 的字符串

这是我的控制器的代码:

        [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;
            }
        }

这是我的 Angular 代码:

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"

而且我还使用了creative-tim的 paper-dashboard-angular 模板

更新:

我上传了示例 web api 和我正在使用的示例角度代码

https://github.com/AngularLearner18/WebAPI

https://github.com/AngularLearner18/Angular

标签: angularasp.net-coreasp.net-web-api2angular7asp.net-core-webapi

解决方案


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 !!');
      });
  }

推荐阅读