0

I have got a Angular Project with a asp.net backend. What I like to do is, to simply post a string to my controller.

I tried the following:

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

Backend:

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

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

This doesnt seem to work. Dont know how to achieve that I just post the string and get it in the backend.

Hope you can help me.

  • Possible duplicate of [How to post a string in the body of a post request with Angular 4.3 HttpClient?](https://stackoverflow.com/questions/47354807/how-to-post-a-string-in-the-body-of-a-post-request-with-angular-4-3-httpclient) – miselking Mar 05 '19 at 14:49
  • @miselking if that would have helped me, I wouldn't post a new question. – kn4ekebrot Mar 05 '19 at 15:13

2 Answers2

0

Try setting Header Content-Type: application/json; charset=utf-8

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

0

The answer was that the string you want to send, needs to be a real string. If you just POST "test", like I did, it wont work. Instead you need to make sure that you get the " within the string so something like this: "\"" + YOUR_STRING + "\"". This will make the POST request send "test" instead of only test. Then it works. Hope someone else will save some time on this.