Angular post 到 asp.net 后端的字符串

Angular post a string to asp.net backend

我有一个带有 asp.net 后端的 Angular 项目。 我喜欢做的是,简单地 post 一个字符串到我的控制器。

我尝试了以下方法:

Angular

constructor(private http: HttpClient, @Inject('BASE_URL') private baseUrl: string) { }

httpOptions = {
  headers: new HttpHeaders({
    'Content-Type': 'application/json'
  })
};

postString(data:string) {
  this.http.post(this.baseUrl + 'api/utility/GetGuid/', "test", this.httpOptions)
  .subscribe((guid: string) => {
     //do something
  });
}

后端:

[Route("api/[controller]")]
public class UtilityController : Controller
{

    [HttpPost]
    [Route("GetGuid")]
    public JsonResult GetGuid([FromBody]string data)
    {
       //do something
    }

这似乎不起作用。 不知道如何实现我只是 post 字符串并在后端获取它。

希望你能帮助我。

尝试设置页眉Content-Type: application/json; charset=utf-8

参考: https://weblog.west-wind.com/posts/2013/dec/13/accepting-raw-request-body-content-with-aspnet-web-api

答案是您要发送的字符串必须是真实的字符串。如果你像我一样只是 POST "test",那是行不通的。相反,您需要确保在字符串中得到 ",这样的东西是这样的:"\"" + YOUR_STRING + "\""。这将使 POST 请求发送 "test" 而不是只测试。然后就可以了。 希望其他人可以节省一些时间。