Home > Back-end >  How can I return post API message?
How can I return post API message?

Time:08-27

I have some messages in the API side. I want to return API Message to user when the "Success" status is false. I was able to print the messages in the get operations, but not in the post operation.

Controller

    [HttpPost]
    public IActionResult AddUser(UserModel userModel, string uniqueUser)
    {
        if (ModelState.IsValid)
        {
            var postTask = _client.PostAsJsonAsync<UserModel>("users/adduser", userModel);
            postTask.Wait();
            var result = postTask.Result;

            if (result.IsSuccessStatusCode)
            {
                return RedirectToAction("AddApplicant", "Applicant", new { uniqueUser = uniqueUser });
            }
        }
        return View();
    }

Response Model

public class ResponseModel
{
    public bool Success { get; set; }
    public string Message { get; set; }
}

User Model

public class UserModel 
{
    public int Id { get; set; }

    [Display(Name = "E-Mail")]
    [Required(ErrorMessage = "{0} field is requried.")]
    [EmailAddress(ErrorMessage = "Your {0} information is not in the correct format.")]
    public string Email { get; set; }

    [Display(Name = "Phone Number")]
    [Required(ErrorMessage = "{0} field is requried.")]
    [RegularExpression(@"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$", ErrorMessage = "Your {0} information is not in correct format.")]
    public string PhoneNumber1 { get; set; }

    [Display(Name = "Second Phone Number")]
    [RegularExpression(@"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$", ErrorMessage = "Your {0} information is not in correct format.")]
    public string PhoneNumber2 { get; set; }

}

API response enter image description here

CodePudding user response:

First and foremost... Use async properly. Don't call .Wait() or .Result directly. Instead, await the task:

[HttpPost]
public async Task<IActionResult> AddUser(UserModel userModel, string uniqueUser)
{
    if (ModelState.IsValid)
    {
        var result = await _client.PostAsJsonAsync<UserModel>("users/adduser", userModel);
        if (result.IsSuccessStatusCode)
        {
            return RedirectToAction("AddApplicant", "Applicant", new { uniqueUser = uniqueUser });
        }
    }
    return View();
}

This will make further interactions with the result much simpler. As for your "message", first you need to deserialize the result:

[HttpPost]
public async Task<IActionResult> AddUser(UserModel userModel, string uniqueUser)
{
    if (ModelState.IsValid)
    {
        var result = await _client.PostAsJsonAsync<UserModel>("users/adduser", userModel);
        if (result.IsSuccessStatusCode)
        {
            // deserialize the response:
            var response = await result.Content.ReadAsStringAsync();
            var responseModel = JsonConvert.DeserializeObject<ResponseModel>(response);

            return RedirectToAction("AddApplicant", "Applicant", new { uniqueUser = uniqueUser });
        }
    }
    return View();
}

Then you can do whatever you like with that .Message property. For example, you can include it in the redirect parameters:

// deserialize the response:
var response = await result.Content.ReadAsStringAsync();
var responseModel = JsonConvert.DeserializeObject<ResponseModel>(response);

return RedirectToAction("AddApplicant", "Applicant", new
    {
        uniqueUser = uniqueUser,
        message = responseModel.Message
    });

Or in something like TempData:

// deserialize the response:
var response = await result.Content.ReadAsStringAsync();
var responseModel = JsonConvert.DeserializeObject<ResponseModel>(response);

TempData["message"] = responseModel.Message;
return RedirectToAction("AddApplicant", "Applicant", new { uniqueUser = uniqueUser });

Overall the pattern is the same. In order to use the Message you first need to read it from the response. Then you can use it however you like.

  • Related