Search code examples
c#asp.net-coreifttt

Why doesn't WebApi config for WebHook work on POST?


i want to get posted data from IFTTT from WebHook. It works when using GET but it doesn't when using POST.

[HttpPost]
[Route("InsertData")]
public IActionResult InsertData([FromBody] string FromAddress)
{
    try
    {
         //var fromAddress = Request.Form["FromAddress"].ToString();
        _webHookDb.UserData.Add(new UserData()
        {  
            FromAddress = FromAddress,
            DateTime = DateTime.Now
        });
        _webHookDb.SaveChanges();
        return new JsonResult(FromAddress);
    }
    catch (Exception ex)
    {
        return BadRequest(ex.Message);
    }
}

Solution

  • Create a model to hold the data

    public class Model {
        public string FromAddress { get; set; }
    }
    

    use that in the action endoint.

    [HttpPost]
    [Route("InsertData")]
    public async Task<IActionResult> InsertData([FromBody] Model model) {
        try {
            if(ModelState.IsValid) {
                _webHookDb.UserData.Add(new UserData() { 
                    FromAddress = model.FromAddress,
                    DateTime = DateTime.Now
                });
                await _webHookDb.SaveChangesAsync();
                return new Ok(model);
            }
            return BadRequest(ModelState); //Bad data?
        } catch (Exception ex) {
            return StatusCode(500, ex.Message); //Something wrong with my code?
        }
    }
    

    Review the message returned from the response in the web-hook to get details about why the request failed.

    If HTTP Status Code 500 then something is wrong with how the data is being saved.

    If HTTP Status Code 400 then something is wrong with how the data is being sent.