Andrian Durlestean
Andrian Durlestean

Reputation: 1730

REST API HttpClient return response good practice

I have methods that are returning objects, the problem is I don't have good idea how to verify errors and return it correctly in MVC View

    public async Task<object> GetUser()
    {
            //....

            if (responseMessage.IsSuccessStatusCode)
            {
                return await responseMessage.Content.ReadAsAsync<User>();
            }
            if (responseMessage.StatusCode == HttpStatusCode.BadRequest)
            {
                return await responseMessage.Content.ReadAsAsync<Error>();
            }
        }
        return null;
    }

Now in my controller I'm getting data and trying to return correct type

var httpResult = await GetUser();
if (httpResult.GetType() == typeof (Error))
{
    ModelState.AddModelError("", (httpResult as Error).ErrorDescription);
    return View(model);
}

if (httpResult.GetType() == typeof (User))
{
    var user = httpResult as User;
    return View(User);
}

I don't like my ifs and logic, any better solution?

Upvotes: 0

Views: 606

Answers (1)

Liviu Mandras
Liviu Mandras

Reputation: 6627

You can try something like this. I used this pattern successfully in the past and present.

[DataContract]
public class OperationResult<T>
{
    [DataMember]
    public List<Error> Errors { get; set; }

    [DataMember]
    public T ResultObject { get; set; }

    [DataMember]
    public bool Success { get; private set; }

    public OperationResult(List<Error> errors)
    {
        Errors = errors;
    }

    public OperationResult(T resultObject)
    {
        ResultObject = resultObject;
        Success = true;
    }

    public OperationResult()
    {

    }
}

You return this type from your methods and you check the Success flag on return, if false you read the Errors property and you can populate the ModelState or return a specialized view model etc.

Upvotes: 2

Related Questions