Home > Enterprise >  RestAPI C# .net core pass a single string to post request. not reaching endpoint
RestAPI C# .net core pass a single string to post request. not reaching endpoint

Time:08-13

I have a very simple need. 1, Send single string to calling endpoint using POST method. 2, Don't want Get request at all. Don't want to create model for incoming/outgoing params .

I have tried almost everything I can find online. most of the example is creating DTO object which seems overkill just to send simple string. Due to size of string, HTTPGet is not recommended. I am getting endpoint NOT FOUND ERROR

[Route("GetVar")]
[HttpPost]
public HttpResponseMessage GetVar([FromBody] string incomingvar)
{                     
return Request.CreateResponse(HttpStatusCode.OK,"10pk" );            
} 

public async Task<HttpResponseMessage> GetVar(string incomingvar)
    {       
        var content = "{\"incomingvar\" : incomingvar}";
        var json = JsonConvert.SerializeObject(content, Formatting.Indented);
        var stringContent = new StringContent(json);
        _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
          return await _httpClient.PostAsync(url, stringContent);
    }


CodePudding user response:

Try doing something like this:

[HttpPost("GetVar")]
public async Task<HttpResponseMessage> GetVar([FromBody] object incomingvar)
{
   //Do work here
}

Then call your method like so: https://localhost:7292/api/controllername/GetVar

Obviously your localhost part and port will be different, but idea is same.

  • Related