Paul
Paul

Reputation: 3283

Internal Server Error from PostAsync

I have the method below which posts data to a URL

    public async Task<IActionResult> PostAsync(string method, string data, bool isJson = true, long key = 0)
    {
        IActionResult result;
        try
        {
            var proxyUrl = await EstablishProxyUrlAsync(method, key).ConfigureAwait(false);
            var content = isJson ? new StringContent(data, Encoding.UTF8, "application/json") : new StringContent(data);

            var response = await this._httpClient.PostAsync(proxyUrl, content).ConfigureAwait(false);
            result = await ProcessResponseAsync(response).ConfigureAwait(false);
        }
        catch (Exception e)
        {
            Log.Error(e, this.GetType().Name + ": Error in PostAsync");
            throw;
        }

        return result;
    }

As you can see I am setting ContentType, loads of posts about dealing with StringContent say about using this method.

However, I just get this back

{StatusCode: 500, ReasonPhrase: 'Internal Server Error', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
  Date: Sun, 29 Jul 2018 19:19:35 GMT
  Server: Kestrel
  Content-Length: 0
}}

This is obviously a pretty useless response in terms of seeing what the problem is

The method being called is below

[HttpPost]
[ActionName("Add")]
public async Task<IActionResult> AddAsync(StringContent content)
{
    var myJson= await content.ReadAsStringAsync().ConfigureAwait(false);
    var object= JsonConvert.DeserializeObject<MyObject>(myJson);
    var result = await _service.AddAsync(object).ConfigureAwait(false);

    return result;
}

As you can see, I have included HttpPost

Does anyone know what could cause this?

I am using service fabric and this URL is one on a partition, but I dont think this is the problem as this routing works in other areas

Paul

Upvotes: 1

Views: 2076

Answers (1)

Nkosi
Nkosi

Reputation: 247333

Method being called should be refactor to follow proper syntax and pass the model to the action and have the model binder populate it with the incoming data.

[HttpPost]
[ActionName("Add")]
public async Task<IActionResult> AddAsync([FromBody] MyObject model) {
    var result = await _service.AddAsync(model);
    return result;
}

with the assumption that _service.AddAsync(model); returns IActionResult when awaited

Reference Model Binding in ASP.NET Core

Upvotes: 3

Related Questions