将 Asp.net Core API 的结果传递给 Angular

Pass the result of Asp.net Core API to Angular

'

我正在学习 ASP.NET CoreAngular

我已经创建了 API (ASP.NET Core)。我可以使用 Angular.

调用 api

这是控制器

[Route("api/[controller]")]
[ApiController]
public class XmlBeautifierController : ControllerBase
{
    private readonly IXmlBeautifier _xmlBeautifier;
    public  XmlBeautifierController(IXmlBeautifier xmlBeautifier)
    {
        _xmlBeautifier = xmlBeautifier;
    }
    [HttpPost("XmlBeautifier")]
    public string XmlBeautifier([FromBody] XmlData data)
    {
        try
        {

            Console.WriteLine(data);

            Console.WriteLine("Parsed XML Data: " + _xmlBeautifier.Beautify(data.Xml));
            //read the content

            return _xmlBeautifier.Beautify(data.Xml);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            Console.WriteLine(ex.StackTrace);
            throw ex;
        }
    }
}

我检查了 api 是否被正确调用。但是当我想读取控制器的结果时。问题来了,这是我不明白的错误

SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse () at XMLHttpRequest.onLoad

我看过一些教程,它说为了读取结果是这样的

onSubmit() {

    // TODO: Use EventEmitter with form value
    console.warn(this.xmlForm.value);
    this.http.post('http://localhost:5000/api/XmlBeautifier/XmlBeautifier', { Xml: this.xmlForm.controls['XmlData'].value })
    .subscribe(res => {
      console.log(res);
      alert('SUCCESS !!');
    })
  }

我的代码有什么问题?

Web API 默认接受 JSON。问题是……这是发送的 json 对象的样子:

{ Xml: <doc><nodes><node>content</node><node>more content</node></nodes></doc> }

您需要做的是:

  1. 用引号将 XmlData 括起来(例如`{ Xml: "'" + this.xmlForm.controls['XmlData'].value + "'" }')
  2. 确保没有提供时髦的引号 - 您可能想在客户端转义非字母数字字符,然后在服务器端取消转义。
  3. 您的控制器应该接受 XmlElement(而不是 XmlData
  4. 将您的 onSubmit() 更新为如下所示:
import { HttpHeaders } from '@angular/common/http';

onSubmit() {

    const httpOptions = {
      headers: new HttpHeaders({
        'Accept', 'application/xml,application/xhtml+xml,text/html'
      })
    };

    // TODO: Use EventEmitter with form value
    console.warn(this.xmlForm.value);
    this.http.post('http://localhost:5000/api/XmlBeautifier/XmlBeautifier', { Xml: this.xmlForm.controls['XmlData'].value }, httpOptions)
    .subscribe(res => {
      console.log(res);
      alert('SUCCESS !!');
    })
  }

这会告诉服务器以 [​​=48=] 而非 JSON 的形式回复您。

最后,根据您的整体 API 配置方式,查看 服务器端应用程序中的其他几个配置选项。

警告: 提交自由格式的 xHTML 非常危险,这就是为什么许多启用了 OWASP 的 firewalls/application 网关会阻止此类内容的原因。我会以某种方式包装您的内容(或像我建议的那样转义)以防止防火墙内出现警告(或阻止)。