Prince
Prince

Reputation: 328

Send json data in Content of httpresponse in .net core API

I am trying to insert multiple users in database using a API. Now, suppose there are three users to be inserted and assume that one user didn't get inserted but other two are suceessfully inserted. So, I have a requirement to show response which shows that user first is successfully inserted , user 2nd have an error. That is why I have useed list of httpResponseMessage and in each httpresponsemessageobject, I will add complete user json indicating that this was the user, who have failed or success status

So, as per my implementation

I am using foreach loop to insert multiple users in db and returning reponse like this but my respose from api do not shows "user" object in content:

public async Task<List<HttpResponseMessage>> InserUsers(JArray obj)
{
List<myDTO> users = obj.ToObject<List<myDTO>>();
List<HttpResponseMessage> list = new List<HttpResponseMessage>();
 foreach (var user in users)
{
    var response = Insert(user);
     list.Add(new HttpResponseMessage
                    {

                        Content = new StringContent(JsonConvert.SerializeObject(user), System.Text.Encoding.UTF8, "application/json"),
                        ReasonPhrase = response.ReasonPhrase,
                        StatusCode = response.StatusCode
                    });

}
return returnResposeList;
}

 public HttpResponseMessage Insert(User user)
{
     // do insert and if there is error

       return new HttpResponseMessage()
                {
                    StatusCode = HttpStatusCode.Error,
                    ReasonPhrase = $"Error"
                };

     else
    {
          return new HttpResponseMessage()
            {
                StatusCode = HttpStatusCode.OK,
                ReasonPhrase = $"Successfully inserted"
            };
    }
}

Thanks & regards

Upvotes: 0

Views: 1173

Answers (2)

Edward
Edward

Reputation: 29966

For HttpResponseMessage, it used to describe the whole response, you should avoid returning HttpResponseMessage with multiple HttpResponseMessage.

For another option, you could try create your own HttpResponseMessage like

public class ApiResponseMessage
{
    //
    // Summary:
    //     Gets or sets the reason phrase which typically is sent by servers together with
    //     the status code.
    //
    // Returns:
    //     The reason phrase sent by the server.
    public string ReasonPhrase { get; set; }
    //
    // Summary:
    //     Gets or sets the status code of the HTTP response.
    //
    // Returns:
    //     The status code of the HTTP response.
    public HttpStatusCode StatusCode { get; set; }
    //
    // Summary:
    //     Gets or sets the content of a HTTP response message.
    //
    // Returns:
    //     The content of the HTTP response message.
    public object Content { get; set; }

}

And then

[HttpPost("InserUsers")]
public async Task<List<ApiResponseMessage>> InserUsers()
{
    List<User> users = new List<User> {
        new User{ Name = "Jack" },
        new User{ Name = "Tom"},
        new User{ Name = "Tony"}
    };
    List<ApiResponseMessage> list = new List<ApiResponseMessage>();
    foreach (var user in users)
    {
        var response = Insert(user);
        list.Add(new ApiResponseMessage
        {

            Content = new { user },
            ReasonPhrase = response.ReasonPhrase,
            StatusCode = response.StatusCode
        });

    }
    return list;
}

public ApiResponseMessage Insert(User user)
{
    // do insert and if there is error
    if (user.Name == "Tom")
    {
        return new ApiResponseMessage()
        {
            StatusCode = HttpStatusCode.BadRequest,
            ReasonPhrase = $"Error"
        };
    }
    else
    {
        return new ApiResponseMessage()
        {
            StatusCode = HttpStatusCode.OK,
            ReasonPhrase = $"Successfully inserted"
        };
    }
}

Upvotes: 1

eVolve
eVolve

Reputation: 1446

As per some of the comments, I don't understand why you need a status code for each insert rather than returning a bool or something like the inserted Id.

I think something like this works with what you have shown already along with return the user objects:

 public async Task<ObjectResult> InserUsers(JArray obj)
    {
        List<myDTO> users = obj.ToObject<List<myDTO>>();
        List<InsertUserResponseDto> list = new List<InsertUserResponseDto>();
        foreach (var user in users)
        {
            var isSuccess = Insert(user);
            list.Add(new InsertUserResponseDto
            {
                User = user,
                StatusCode = isSuccess ? StatusCodes.Status200OK : StatusCodes.Status500InternalServerError,
            });

        }

        var isSuccessfullInsert = list.Any(x => x.StatusCode == StatusCodes.Status207MultiStatus);
        return StatusCode(isSuccessfullInsert ? StatusCodes.Status207MultiStatus : StatusCodes.Status200OK, list);
    }

    public bool Insert(User user)
    {
        try
        {
            // Complete insert
            return true;
        }
        catch (Exception ex)
        {
            // Log Exception
            return false;
        }
    }

    public class InsertUserResponseDto
    {
        public User User { get; set; }
        public int StatusCode { get; set; }
    }

I have used the response code of 207 if any of the inserts fail otherwise I have used a 200. Each object within the list will contain the original user object along with an associated status code that you wanted including handling for success and failure.

Upvotes: 1

Related Questions