2
\$\begingroup\$

This class is actually a wrapper around HttpWebRequest to issue a POST request with some payloads:

public class SendMessageService
{
    public async Task Send()
    {
        var request = WebRequest.Create("url") as HttpWebRequest;

        request.Method = "POST";
        request.ContentType = "application/json; charset=utf-8";

        request.Headers["authorization"] = "token";

        byte[] byteArray = Encoding.UTF8.GetBytes("{"
                                                + "\"app_id\": \"appId\","
                                                + "\"extra_parameter\": \"value\"}");

        string responseContent = null;

        try
        {
            using (var writer = await request.GetRequestStreamAsync())
            {
                writer.Write(byteArray, 0, byteArray.Length);
            }

            using (var response = await request.GetResponseAsync() as HttpWebResponse)
            {
                using (var reader = new StreamReader(response.GetResponseStream()))
                {
                    responseContent = await reader.ReadToEndAsync();
                }
            }
        }
        catch (WebException ex)
        {
            System.Diagnostics.Debug.WriteLine(ex.Message);
            System.Diagnostics.Debug.WriteLine(new StreamReader(ex.Response.GetResponseStream()).ReadToEnd());
        }

        System.Diagnostics.Debug.WriteLine(responseContent);
    }
}

this class is going to be used in a web environment (ASP.NET Core app) so I registered this service as transient (created each time it is requested):

services.AddTransient<SendMessageService, SendMessageService>();

I would appreciate any improvement suggestions.

\$\endgroup\$
1
  • \$\begingroup\$ Please please please please please do not swallow exceptions. Writing them to the debug output is tantamount to ignoring them. Raise the exception. Let the method call fail. Do not hide exceptions! \$\endgroup\$ Commented Jun 12, 2017 at 16:28

1 Answer 1

1
\$\begingroup\$

Name the method SendAsync since it is meant to be used asynchronously. Since this is in a web app, all awaited calls should chain to .ConfigureAwait(false). Also, since you're async, use await writer.WriteAsync rather than writer.Write. A few more Streams need to be wrapped in using statements. Don't swallow exceptions -- Logging them is all right. Method does not seem to access any instance data, so it could be static and therefore the class it is in can be as well. Here is a rewrite:

    public static async Task SendAsync()
    {
        var request = WebRequest.Create("url") as HttpWebRequest;

        if (request == null)
        {
            return;
        }

        request.Method = "POST";
        request.ContentType = "application/json; charset=utf-8";

        request.Headers["authorization"] = "token";

        var byteArray = Encoding.UTF8.GetBytes("{"
                                                  + "\"app_id\": \"appId\","
                                                  + "\"extra_parameter\": \"value\"}");

        string responseContent = null;

        try
        {
            using (var writer = await request.GetRequestStreamAsync().ConfigureAwait(false))
            {
                await writer.WriteAsync(byteArray, 0, byteArray.Length).ConfigureAwait(false);
            }

            using (var response = await request.GetResponseAsync().ConfigureAwait(false) as HttpWebResponse)
            {
                if (response != null)
                {
                    using (var responseStream = response.GetResponseStream())
                    {
                        if (responseStream != null)
                        {
                            using (var reader = new StreamReader(responseStream))
                            {
                                responseContent = await reader.ReadToEndAsync().ConfigureAwait(false);
                            }
                        }
                    }
                }
            }
        }
        catch (WebException ex)
        {
            System.Diagnostics.Debug.WriteLine(ex.Message);
            if (ex.Response != null)
            {
                using (var responseStream = ex.Response.GetResponseStream())
                {
                    if (responseStream != null)
                    {
                        using (var reader = new StreamReader(responseStream))
                        {
                            System.Diagnostics.Debug.WriteLine(await reader.ReadToEndAsync().ConfigureAwait(false));
                        }
                    }
                }
            }

            throw;
        }

        System.Diagnostics.Debug.WriteLine(responseContent ?? string.Empty);
    }
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.