【问题标题】:how to pass string from Angular to .NET Core WebAPI and get json in return?如何将字符串从 Angular 传递到 .NET Core WebAPI 并获取 json 作为回报?
【发布时间】:2020-12-03 07:45:50
【问题描述】:

大家!

我想从我的前端发送字符串,我使用 Angular9。代码如下:

const word: string = this.str;
console.log(word);
this.http.post(this.myurl, word)
  .subscribe(data => {
    console.log(data);
    // console.log(this.value)
  });

变量word包含字符串(word),通过post请求发送到服务器。 this.myurl 是 URL 字符串,由服务器 URL 组成。 我的后端应该接收并计算这个(单词)字符串。之后,它应该将 json 字符串返回到前面。代码如下:

 [HttpPost]
    public async Task<ActionResult<string>> Adding([FromBody] string word)
    {
       
        string json = string.Empty;
       //some calculations with **word** after which I will get dictionary.
        json = JsonConvert.SerializeObject(dictionary);
        
      //some calculations
        return json;
    }

所以,问题是,Angular 在控制台中报告 415 错误。我知道如何在不订阅的情况下发出 post 请求,而我不明白如何在 post 请求中接收 Angular 中的 json。每次我从服务器获得不同的 json 字符串(它实际上取决于你从前面发送的字符串),所以,我不能为此目的构造静态模型。 无论如何,如果你能帮助我解决这个问题,我将非常感激。

【问题讨论】:

  • 只要返回对象,框架会为你序列化。这才是重点。我相信从 body 正在寻找一个对象中称为 word 的属性。

标签: c# .net angular asp.net-web-api .net-core


【解决方案1】:

对于那些,你可能和我有同样的问题,这里是解决方案: 首先,谢谢亲爱的 Aluan Haddad,我按照你的提示,所以,我在我的后端创建了模型(Model.cs,它只包含一个 string 属性),然后,我将此模型的对象作为我的控制器的参数:

public async Task<ActionResult<ModelWord>> Endings(Model model)
        {
//....
}

作为返回值,这个方法只是重定向到带有 json 数据的 GET 控制器,而我前面从 Get 方法(控制器)获取数据。

在我的 Angular 中,我也用一个字符串创建了模型。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-28
    • 1970-01-01
    • 2019-11-11
    • 1970-01-01
    • 2021-06-13
    • 1970-01-01
    • 2015-04-17
    相关资源
    最近更新 更多