WebAPI is returning 200 but the SendAsync call shows 500

2.5k views Asked by At

I have an MVC application that calls a WebAPI async, both on POST and GET. When running both the WebAPI and MVC applications locally, the WebAPI response shows successful but the SendAsync request returns 500. Also, Fiddler doesn't show the API call. I have a suspicion that it has to do with how the async request is being handled, but I'm not sure what I'm missing.

MVC Controller call to the API:

public Model UploadFile(Model formCollection)
{
    var documentModel = formCollection.ToString();

    var client = new HttpClient();
    var uri = new Uri(BaseUri + "document/");

    var content = new StringContent(documentModel);

    var request = new HttpRequestMessage(HttpMethod.Post, uri) {Content = content};

    request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

    var response = client.SendAsync(request);
    response.Wait();

    try
    {
        var returned = response.Result;
        if (returned.StatusCode != HttpStatusCode.OK)
        {
            throw new Exception(returned.RequestMessage.ToString());
        }

        var model = JsonConvert.DeserializeObject<Model>    (returned.Content.ReadAsStringAsync().Result);
        model.FileContents = "";

        return model;
    }
    catch(Exception e)
    {
        var error = new Exception("Service failure - ", e);
        throw error;
    }
}

The WebAPI Post:

[HttpPost]
public async Task<HttpResponseMessage> Post([FromBody]Model model)
{
    var response = await SubmitNew(model);

    return Request.CreateResponse(response);
}

Setting the breakpoint on the return in the Post shows a valid response, but on the response.Result in the MVC Controller it shows 500. I've even tried returning an OK request no matter the response as below:

return Request.CreateResponse(HttpStatusCode.OK, result);

Any ideas as to why the client is showing 500?

3

There are 3 answers

0
Kirby Kernen On BEST ANSWER

I found the issue, there was a timeout error in the WebAPI's logging service that was happening after the initial POST and GET calls result.. Issue is resolved.

0
Zenilogix On

In your Global.asax.cs

public class WebApiApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        // Try adding the following lines:
        var configuration = GlobalConfiguration.Configuration;
        var formatters = configuration.Formatters;
        formatters.Clear();
        formatters.Add(new JsonMediaTypeFormatter());
    }

    // A good idea to have this:
    protected void Application_Error()
    {
        Exception unhandledException = Server.GetLastError();
        // Set a breakpoint here or do something to log the exception
    }

The code added to Application_Start will ensure that serialization is only to/from JSON. While it may not be what you want in your final code, it may be helpful as a temporary measure to isolate the cause of your problem.

Adding Application_Error should help to catch issues which occur within the WebAPI layer, such as when it serializes the object you've returned from your controller method.

My suspicion is that SubmitNew is returning something which cannot be serialized such as an infinitely recursive reference (example: parent/child structure with mutual references).

0
Liam On

I had a similar issue with some code that I "improved" - I saw HttpResponseMessage implements the IDisposable interface so decided to wrap the Return Request.CreateResponse method is a using statement, leading to a 500 error.

Removing the using statement fixed the issue for me.