API Controller Post method return type/value

SkyeBoniwell picture SkyeBoniwell · Apr 10, 2017 · Viewed 9.4k times · Source

I want to use a .NET Web API 2 Controller for my vb.net game.

I added one to my project and I updated my Global.axax.vb & Application_Start method per the instructions.

Right now I'm just trying to figure out how it works.

But I don't know what to return or how to return with my Controller method.

This is my test ajax method:

<script>
    $("#btnUpdate").click(function(e) {

        var Data = {};
        Data.test1 = "testVal1";
        Data.test2 = "testVal2";

        $.ajax({
            url: 'api/GameData',
            method: 'POST',
            dataType: 'json',
            contentType: 'application/json; charset=utf-8',
            data: Data,
            success: function(data) {
                alert("Saved successfully");
            },
            fail: function(jqXHR, textStatus) {
                alert("Request failed: " + textStatus);
            }
        });
    });
</script>

This is my empty PostValue method that Visual Studio generated:

    ' POST: api/GameData
    Public Sub PostValue(<FromBody()> ByVal value As String)
        'what type of return value?
    End Sub

What should this method return?

Thanks!

Answer

Kaushal picture Kaushal · Apr 10, 2017

Depending on scenario it can return one of following

  1. void --> http response will be 204

  2. HttpResponseMessage

  3. IHttpActionResult

  4. Serialized return body for http reponse 200

Generally, Http POST api return 201 created with resource created. Example

Public Function PostValue(<FromBody> value As String) As IHttpActionResult
    Dim product = New With {Key .Name = "Watch", .Price = 250}
    return Content(HttpStatusCode.Created, product, new JsonMediaTypeFormatter())
End Function

For details will example