Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WebApi2 IHttpActionResult strongly typed return values

It is possible and not ideal to do this: (a vastly simplified example!)

[Serializable]
public class MyRecord
{
    public string key {get; set;}
    public string data {get; set;}
}

public async Task<IHttpActionResult> Get(string SomeKey)
{
    if(ExistsInDB(SomeKey))
    {
        return Ok(SomeRecordFromDB(SomeKey));  //SomeRecord() returns a POCO MyRecord.
    }
    else
    {
        //I know I can return NotFound() but not the focus of my Q
        return Ok(false);  //returns "False"
    }
}

Effectively demonstrating no compile time error checking on the return type. This example will return either a JSon serialized POCO class (JSon is set on my accept header) or it will return the text "False" which puts the burden of type checking on the client.

I wouldn't do this by design but my team is refactoring a lot of code from asmx/svc and mistakes creep in. I like it when the compiler helps to trap these kinds of errors rather than waiting for module or unit testing.

Is the right way to go back to using strongly typed method signatures (avoiding the IHttpActionResult and the Ok(), NotFound(), etc helpers or is there something like a IHttpActionResult<T> that can be used to make sure the right type is being returned?

M.

like image 509
MarkD Avatar asked Oct 28 '16 07:10

MarkD


2 Answers

First of all, it is a good practice to return IHttpActionResult, indicating the corresponding http status. Something like:

public async Task<IHttpActionResult> Get(string SomeKey)
{
    if(ExistsInDB(SomeKey))
        return Ok(SomeRecordFromDB(SomeKey));

    return NotFound();
}

But if you really want to have a strongly typed api, you can do something like:

 public async Task<StronglyTypeResponse> Get()
 {
     return new StronglyTypeResponse();
 }

Or, create a typed response, and you'll keep the http status code, etc in your response:

public class StronglyTypeResponse
{

}

public class StronglyTypedResult<T> : IHttpActionResult
{
    HttpConfiguration _configuration;
    T _content;
    HttpStatusCode _statusCode;
    HttpRequestMessage _request;

    public StronglyTypedResult(T content, HttpStatusCode statusCode, HttpRequestMessage request, HttpConfiguration configuration)
    {
        _content = content;
        _request = request;
        _configuration = configuration;
        _statusCode = statusCode;
    }

    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        var response = new HttpResponseMessage(_statusCode)
        {
            Content = new ObjectContent<dynamic>(_content, _configuration.Formatters.JsonFormatter),
            RequestMessage = _request,
            ReasonPhrase = "some phrase"
        };

        return Task.FromResult(response);
    }
}

And then you can create your method:

public async Task<StronglyTypedResult<StronglyTypeResponse>> Get()
{
    return new StronglyTypedResult<StronglyTypeResponse>(new StronglyTypeResponse(), HttpStatusCode.OK, Request, Configuration);
}

Creating your own custom generic IHttpActionResult

It's basically the same:

public class IHttpActionResult<T> : System.Web.Http.IHttpActionResult
{
    HttpConfiguration _configuration;
    T _content;
    HttpStatusCode _statusCode;
    HttpRequestMessage _request;

    public IHttpActionResult(T content, HttpStatusCode statusCode, HttpRequestMessage request, HttpConfiguration configuration)
    {
        _content = content;
        _request = request;
        _configuration = configuration;
        _statusCode = statusCode;
    }

    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        var response = new HttpResponseMessage(_statusCode)
        {
            Content = new ObjectContent<dynamic>(_content, _configuration.Formatters.JsonFormatter),
            RequestMessage = _request,
            ReasonPhrase = "some phrase"
        };

        return Task.FromResult(response);
    }
}

And now you can return the class you want with a typed IHttpActionResult:

public async Task<IHttpActionResult<YourClass>> Get()
{
    var yourclass = new YourClass();

    return new IHttpActionResult<YourClass>(yourclass, HttpStatusCode.OK, Request, Configuration);
}
like image 144
Rafael Marques Avatar answered Oct 17 '22 02:10

Rafael Marques


The problem with using strongly typed method signatures is that there is no way for you to return an "error" object if something is wrong with the request, be it validation errors or not found errors.

So if you want to use strongly typed signatures then you either have to included some sort of "error" object reference in your return type or explicitly throw exceptions..

The good thing about using HttpActionResult is that you are not constrained to a specific return type. So you could, for example, return OK(someObject) or BadRequest(errorObject). However, it is up to the developer to write the method correctly and double check that nothing happens like the example you mentioned above.

like image 30
Draco Avatar answered Oct 17 '22 01:10

Draco