none
C# rewrite Restsharp Windows Form Program to Console Program RRS feed

  • Question

  • Hi, I want to rewrite a Windows Form program, which uses Restsharp asynchronously, to a console program.  As I need to add another async UDP functions.  The original Windows Form program can be found here: https://github.com/cenksari/restsharp-apicaller

    The Windows Form program works in my Visual Studio 2017 Environment.

    The following is my code:

    using Newtonsoft;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Linq;
    using RestSharp;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Text.RegularExpressions;
    using System.Threading;
    using System.Threading.Tasks;
    using static AsyncRest1.ApiCaller;
    
    namespace AsyncRest1
    {
    
        public class ApiCaller
        {
            string apiAddress;
    
            public class RestResponse
            {
                public bool Status { get; set; }
                public string Message { get; set; }
                public string Response { get; set; }
                public string ErrorCode { get; set; }
            }
    
            public class RestRequestA
            {
                public string Method { get; set; }
                public string Endpoint { get; set; }
                public string Payload { get; set; }
                public string Session_Token { get; set; }
            }
    
            public ApiCaller()
            {
                apiAddress = "https://webserver/v1";
            }
    
            public async Task<RestResponse> GetEndpoint(RestRequestA apiRequest)
            {
                RestResponse returnedValue = new RestResponse();
                RestClient client = new RestClient();
                client.BaseUrl = new Uri(apiAddress);
                RestSharp.RestRequest request = new RestSharp.RestRequest(apiRequest.Endpoint);
                request.Method = (apiRequest.Method == "POST") ? Method.POST : Method.GET;
                request.AddHeader("accept", "application/json");
                request.AddHeader("content-type", "application/json");
                request.AddHeader("x-authentication", apiRequest.Session_Token);
                if (request.Method == Method.POST)
                {
                    request.AddParameter("application/json", apiRequest.Payload, ParameterType.RequestBody);
                }
                var cancellationTokenSource = new CancellationTokenSource();
                var response = await client.ExecuteTaskAsync
                (
                    request,
                    cancellationTokenSource.Token
                );
    
                if (response.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    returnedValue.Status = true;
                    returnedValue.Response = response.Content;
                }
                else
                {
                    returnedValue.Status = false;
                    returnedValue.Message = $"{response.StatusDescription} {response.ErrorMessage}";
                    returnedValue.Response = response.Content;
                    returnedValue.ErrorCode = response.StatusCode.ToString();
                }
                return returnedValue;
            }
        }
    
    class Program
    {
    public void Main()
    {
    var api1 = new ApiCaller();
    string token1 = "3699be21-09c8-4fa1-b2ad-9841d31c30";
    string payload1 = @"{ ""Name"": ""John Doe""} ";
    ApiCaller.RestRequestA request1 = new ApiCaller.RestRequestA
    {
    Method = "POST",
    Endpoint = "https://webserver/v1",
    Payload = payload1,
    Session_Token = token1
    };
    
    var response1 = await api1.GetEndpoint(request1);            
    Console.ReadKey();
    }
    }
    }

    Since the returned result from GetEndpoint is JSon data, so I need Newtonsoft.Json to parse the result.  Now I setup my project to use .NET Framework 4.7.1 and C# Version to C# 7.3 (I believe it is the highest version now), and my IDE is Visual Studio 2017 15.7.4, My OS version is Windows 10 Enterprise with latest updates.

    However, my program got compiler error:

    Error CS4033 The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.

    This error seems want me to change public void Main()

    To some thing like: public async Task MainAsync()

    But if I do so, then I got another compiler error:

    Program does not contain a static 'Main' method suitable for an entry point.

    Any advice?  By the way, for the class RestResponse, I don’t need all information, if there is no error in receiving the response from the HTTPS server, I need only the response’s Content.

    By the way, if I use the synchronous way of RestSharp, I can finish the same job without any issue.  However, since I have another UDP asynchronous job (receive UDP packets) to do in the same project.  So, I have to use RestSharp in an asynchronous way.

    Thanks,


    Thursday, July 12, 2018 7:54 PM

All replies

  • You are attempting to use await inside a non-async method. Based upon your code the await call is inside Main so Main needs to be async.

    static async Task Main ( string[] args )
    {
       await Task.Delay(1000);
    }
    Note that to use an async Main you have to target C# 7.1 or higher. The default is to target 7.0 so you'll have to go to your project's properties, go to the Build\Advanced section and change the language version to C# latest minor version.


    Michael Taylor http://www.michaeltaylorp3.net

    Friday, July 13, 2018 2:41 PM
    Moderator
  • Hi,

    Thank you for your advice, I modified my code for the Main part, so the code now looks like:

    static async Task Main(string[] args)
    {
    await Task.Delay(1000);
    var api1 = new ApiCaller();
    string token1 = "3699be21-09c8-4fa1-b2ad-9841d31c30";
    string payload1 = @"{ ""Name"": ""John Doe""} ";
    ApiCaller.RestRequestA request1 = new ApiCaller.RestRequestA
    {
    Method = "POST",
    Endpoint = "https://webserver/v1",
    Payload = payload1,
    Session_Token = token1
    };
    
    // How to get the result from api1.GetEndpoint(request1)?
    // var response1 = await api1.GetEndpoint(request1);            
    
    Console.ReadKey();
    }
    }
    }
    

    The code can run, but how I can get the result, the HTTP POST response?  Now I already set my C# to target C# version 7.3, so don't worry about the C# version now.

    Any suggestion?

    Friday, July 13, 2018 4:40 PM
  • You're using a third party library so I cannot really answer that question. You should post in their forums. Just on a cursory glance at the GitHub code you should uncomment out that var response1 line you had and that will return back the response. Since you're using await the actual result would be RestResponse. At that point you're in RestSharp land and would need to post questions in their forums about how to use their library.


    Michael Taylor http://www.michaeltaylorp3.net

    Friday, July 13, 2018 5:10 PM
    Moderator