Can';在WinForms中不执行来自模块的API调用

Can';在WinForms中不执行来自模块的API调用,winforms,Winforms,当我的启动是模块时,api调用只会完全终止应用程序。我需要我的入口点是一个模块。我怎样才能做到这一点 Module EDIDownloaderModule Sub Main(args As String()) ProcessApi() End Sub Private Async Sub ProcessApi() Dim apiUrl As String = "http://localhost:3554/MWAPI/Projects/Ge

当我的启动是模块时,api调用只会完全终止应用程序。我需要我的入口点是一个模块。我怎样才能做到这一点

Module EDIDownloaderModule

    Sub Main(args As String())
        ProcessApi()
    End Sub

    Private Async Sub ProcessApi()
        Dim apiUrl As String = "http://localhost:3554/MWAPI/Projects/GetProjectByCustomerAndOrderIds?customerId=abc&customerOrderId=xyz"

        Dim apiResult As ApiCallResult(Of Project) = Await ApiCrudCallHelper.Get(Of Project)(apiUrl)
        Dim msg As String = apiResult.Message
    End Sub

End Module
当我的启动是一个表单时,我可以毫无问题地进行api调用

Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        ProcessApi()
    End Sub

    Private Async Sub ProcessApi()
        Dim apiUrl As String = "http://localhost:3554/API/Projects/GetByCustomerAndOrder?customerId=abc&customerOrderId=xyz"

        Dim apiResult As ApiCallResult(Of Project) = Await ApiCrudCallHelper.Get(Of Project)(apiUrl)
        Dim msg As String = apiResult.Message
    End Sub

End Class
下面是API调用的帮助程序代码

   public class ApiCallResult<X> where X : class
    {
        public HttpStatusCode StatusCode { get; set; }
        public string ReasonPhrase { get; set; }

        public bool IsError { get; set; }
        public bool IsException { get; set; }
        public string Message { get; set; }

        public X ResponseObject { get; set; } //deserialized object, could be List, int string or just a single object
    }


   public static class ApiCrudCallHelper
    {
        /// <summary>
        /// Performs Post and returns ApiCallResult
        /// </summary>
        /// <typeparam name="T">model to Post, could be null, T, List T</typeparam>
        /// <typeparam name="X">return model by API, could be X, List X, string </typeparam>
        /// <param name="data">data to post of type T, List T</param>
        /// <param name="apiUrl">api full URL like http://localhost:65152/API/Test if executing custom action, provide that as well at the end </param>
        /// <returns>
        /// ApiCallResult
        ///     StatusCode: status code returned by the API
        ///     ReasonPhrase: reason phrase returned by the API
        ///     IsError: true/false
        ///     IsException: true/false
        ///     Message: error message, exception message, or result of OK etc results by API
        ///     X ResponseObject: model returned by the API, it might not be available in all cases. Could be X, List X or string as provided by X above
        /// </returns>
        public static async Task<ApiCallResult<X>> Post<T, X>(T data, string apiUrl) where X : class
        {
            var apiCallResult = new ApiCallResult<X> { IsError = true, Message = "No run" };
            try
            {
                //json string 
                var jsonString = JsonConvert.SerializeObject(data);
                using (var client = new HttpClient())
                {
                    var httpContent = new StringContent(jsonString, Encoding.UTF8, "application/json");
                    var response = await client.PostAsync(apiUrl, httpContent);
                    var jsonResponseString = await response.Content.ReadAsStringAsync();

                    //fill
                    if (response.IsSuccessStatusCode)
                    {
                        //deserialize
                        if (!typeof(X).Equals(typeof(string)))
                        {
                            apiCallResult.ResponseObject = JsonConvert.DeserializeObject<X>(jsonResponseString);
                        }
                        apiCallResult.IsError = false;
                    }
                    else
                    {
                        try
                        {
                            ApiErrorMessage myMessage = JsonConvert.DeserializeObject<ApiErrorMessage>(jsonResponseString);
                            if (!string.IsNullOrWhiteSpace(myMessage?.Message))
                            {
                                jsonResponseString = myMessage.Message;
                            }
                        }
                        catch (Exception e)
                        {}
                        jsonResponseString = jsonResponseString.Trim('"');
                    }
                    apiCallResult.StatusCode = response.StatusCode;
                    apiCallResult.ReasonPhrase = response.ReasonPhrase;
                    apiCallResult.Message = jsonResponseString;
                }
            }
            catch (Exception ex)
            {
                apiCallResult.IsException = true;
                apiCallResult.Message = ex.Message;
            }

            return apiCallResult;
        }

        /// <summary>
        /// Performs Put and returns ApiCallResult
        /// </summary>
        /// <typeparam name="T">model to Post, could be null, T, List T</typeparam>
        /// <typeparam name="X">return model by API, could be X, List X, string </typeparam>
        /// <param name="data">data to post of type T, List T</param>
        /// <param name="apiUrl">api full URL including the Id like http://localhost:65152/API/Test/12345 if executing custom action, provide that as well </param>
        /// <returns>
        /// ApiCallResult
        ///     HttpStatusCode StatusCode: status code returned by the API
        ///     string ReasonPhrase: reason phrase returned by the API
        ///     bool IsError: true/false
        ///     bool IsException: true/false
        ///     string Message: error message, exception message, or result of OK etc results by API
        ///     X ResponseObject: model returned by the API, it might not be available in all cases. Could be X, List X or string as provided by X above
        /// </returns>
        public static async Task<ApiCallResult<X>> Put<T, X>(T data, string apiUrl) where X : class
        {
            var apiCallResult = new ApiCallResult<X> { IsError = true, Message = "No run" };
            try
            {
                //json string 
                var jsonString = JsonConvert.SerializeObject(data);
                using (var client = new HttpClient())
                {
                    var httpContent = new StringContent(jsonString, Encoding.UTF8, "application/json");
                    var response = await client.PutAsync(apiUrl, httpContent);
                    var jsonResponseString = await response.Content.ReadAsStringAsync();

                    //fill
                    if (response.IsSuccessStatusCode)
                    {
                        //deserialize
                        if (!typeof(X).Equals(typeof(string)))
                        {
                            apiCallResult.ResponseObject = JsonConvert.DeserializeObject<X>(jsonResponseString);
                        }
                        apiCallResult.IsError = false;
                    }
                    else
                    {
                        try
                        {
                            ApiErrorMessage myMessage = JsonConvert.DeserializeObject<ApiErrorMessage>(jsonResponseString);
                            if (!string.IsNullOrWhiteSpace(myMessage?.Message))
                            {
                                jsonResponseString = myMessage.Message;
                            }
                        }
                        catch (Exception e)
                        { }
                        jsonResponseString = jsonResponseString.Trim('"');
                    }
                    apiCallResult.StatusCode = response.StatusCode;
                    apiCallResult.ReasonPhrase = response.ReasonPhrase;
                    apiCallResult.Message = jsonResponseString;
                }
            }
            catch (Exception ex)
            {
                apiCallResult.IsException = true;
                apiCallResult.Message = ex.Message;
            }

            return apiCallResult;
        }

        /// <summary>
        /// Performs Delete and returns ApiCallResult
        /// </summary>
        /// <typeparam name="X">return model by API, could be X, List X, string. Usually you'll only get Ok result etc for delete, so specify string  </typeparam>
        /// <param name="apiUrl">api full URL including the Id like http://localhost:65152/API/Test/12345 if executing custom action, provide that as well </param>
        /// <returns>
        /// ApiCallResult
        ///     HttpStatusCode StatusCode: status code returned by the API
        ///     string ReasonPhrase: reason phrase returned by the API
        ///     bool IsError: true/false
        ///     bool IsException: true/false
        ///     string Message: error message, exception message, or result of OK etc results by API
        ///     X ResponseObject: will only be available if api is returning a model (should not), in most cases it will not be available. Could be X, List X or string as provided by X above
        /// </returns>
        public static async Task<ApiCallResult<X>> Delete<X>(string apiUrl) where X : class
        {
            var apiCallResult = new ApiCallResult<X> { IsError = true, Message = "No run" };
            try
            {
                using (var client = new HttpClient())
                {
                    var response = await client.DeleteAsync(apiUrl);
                    var jsonResponseString = await response.Content.ReadAsStringAsync();

                    //fill
                    if (response.IsSuccessStatusCode)
                    {
                        //deserialize
                        if (!typeof(X).Equals(typeof(string)))
                        {
                            apiCallResult.ResponseObject = JsonConvert.DeserializeObject<X>(jsonResponseString);
                        }
                        apiCallResult.IsError = false;
                    }
                    else
                    {
                        try
                        {
                            ApiErrorMessage myMessage = JsonConvert.DeserializeObject<ApiErrorMessage>(jsonResponseString);
                            if (!string.IsNullOrWhiteSpace(myMessage?.Message))
                            {
                                jsonResponseString = myMessage.Message;
                            }
                        }
                        catch (Exception e)
                        { }
                        jsonResponseString = jsonResponseString.Trim('"');
                    }
                    apiCallResult.StatusCode = response.StatusCode;
                    apiCallResult.ReasonPhrase = response.ReasonPhrase;
                    apiCallResult.Message = jsonResponseString;
                }
            }
            catch (Exception ex)
            {
                apiCallResult.IsException = true;
                apiCallResult.Message = ex.Message;
            }

            return apiCallResult;
        }

        /// <summary>
        /// Performs Get and returns ApiCallResult
        /// </summary>
        /// <typeparam name="X">return model by API, could be X, List X, string. </typeparam>
        /// <param name="apiUrl">api full URL </param>
        /// <returns>
        /// ApiCallResult
        ///     HttpStatusCode StatusCode: status code returned by the API
        ///     string ReasonPhrase: reason phrase returned by the API
        ///     bool IsError: true/false
        ///     bool IsException: true/false
        ///     string Message: error message, exception message, or result of OK etc results by API
        ///     X ResponseObject: Could be X, List X or string as provided by X above
        /// </returns>
        public static async Task<ApiCallResult<X>> Get<X>(string apiUrl) where X : class
        {
            var apiCallResult = new ApiCallResult<X> { IsError = true, Message = "No run" };
            try
            {
                using (var client = new HttpClient())
                {
                    var response = await client.GetAsync(apiUrl);
                    var jsonResponseString = await response.Content.ReadAsStringAsync();

                    //fill
                    if (response.IsSuccessStatusCode)
                    {
                        //deserialize
                        if (!typeof(X).Equals(typeof(string)))
                        {
                            apiCallResult.ResponseObject = JsonConvert.DeserializeObject<X>(jsonResponseString);
                        }
                        apiCallResult.IsError = false;
                    }
                    else
                    {
                        try
                        {
                            ApiErrorMessage myMessage = JsonConvert.DeserializeObject<ApiErrorMessage>(jsonResponseString);
                            if (!string.IsNullOrWhiteSpace(myMessage?.Message))
                            {
                                jsonResponseString = myMessage.Message;
                            }
                        }
                        catch (Exception e)
                        { }
                        jsonResponseString = jsonResponseString.Trim('"');
                    }
                    apiCallResult.StatusCode = response.StatusCode;
                    apiCallResult.ReasonPhrase = response.ReasonPhrase;
                    apiCallResult.Message = jsonResponseString;
                }
            }
            catch (Exception ex)
            {
                apiCallResult.IsException = true;
                apiCallResult.Message = ex.Message;
            }

            return apiCallResult;
        }
    }
public类ApiCallResult其中X:class
{
公共HttpStatusCode状态码{get;set;}
公共字符串{get;set;}
公共布尔IsError{get;set;}
公共布尔IsException{get;set;}
公共字符串消息{get;set;}
public X ResponseObject{get;set;}//反序列化对象,可以是List、int字符串,也可以是单个对象
}
公共静态类ApiCrudCallHelper
{
/// 
///执行Post并返回ApiCallResult
/// 
///要发布的模型,可以为null,T,List T
///通过API返回模型,可以是X,列表X,字符串
///发送到T类邮件的数据,列表T
///api完整URL-likehttp://localhost:65152/API/Test 如果执行自定义操作,请在末尾提供该操作
/// 
///最终结果
///StatusCode:API返回的状态代码
///ReasonPhrase:API返回的原因短语
///IsError:对/错
///IsException:对/错
///消息:错误消息、异常消息或API确定等结果的结果
///X ResponseObject:API返回的模型,可能并非在所有情况下都可用。可以是X、列表X或上面X提供的字符串
/// 
公共静态异步任务Post(T数据,字符串APIRL),其中X:class
{
var apiCallResult=new apiCallResult{IsError=true,Message=“No run”};
尝试
{
//json字符串
var jsonString=JsonConvert.SerializeObject(数据);
使用(var client=new HttpClient())
{
var httpContent=newstringcontent(jsonString,Encoding.UTF8,“application/json”);
var response=wait client.PostAsync(apirl,httpContent);
var jsonResponseString=await response.Content.ReadAsStringAsync();
//填满
if(响应。IsSuccessStatusCode)
{
//反序列化
如果(!typeof(X).Equals(typeof(string)))
{
apiCallResult.ResponseObject=JsonConvert.DeserializeObject(jsonResponseString);
}
apiCallResult.IsError=false;
}
其他的
{
尝试
{
apErrorMessage myMessage=JsonConvert.DeserializeObject(jsonResponseString);
如果(!string.IsNullOrWhiteSpace(myMessage?.Message))
{
jsonResponseString=myMessage.Message;
}
}
捕获(例外e)
{}
jsonResponseString=jsonResponseString.Trim(“”);
}
apiCallResult.StatusCode=response.StatusCode;
apiCallResult.ReasonPhrase=response.ReasonPhrase;
Message=jsonResponseString;
}
}
捕获(例外情况除外)
{
apiCallResult.IsException=true;
apiCallResult.Message=ex.Message;
}
返回结果;
}
/// 
///执行Put并返回ApiCallResult
/// 
///要发布的模型,可以为null,T,List T
///通过API返回模型,可以是X,列表X,字符串
///发送到T类邮件的数据,列表T
///api完整URL,包括Id,如http://localhost:65152/API/Test/12345 如果执行自定义操作,也提供该操作
/// 
///最终结果
///HttpStatusCode状态码:API返回的状态码
///字符串ReasonPhrase:API返回的原因短语
///布尔-伊瑟罗:对/错
///bool IsException:真/假
///字符串消息:错误消息、异常消息或API确定等结果的结果
///X ResponseObject:API返回的模型,可能并非在所有情况下都可用。可以是X、列表X或上面X提供的字符串
/// 
公共静态异步任务Put(T数据,字符串apirl),其中X:class
{
var apiCallResult=new apiCallResult{IsError=true,Message=“No run”};
尝试
{
//json字符串
var jsonString=JsonConvert.SerializeObject(数据);
使用(var client=new HttpClient())
{
var httpContent=newstringcontent(jsonString,Encoding.UTF8,“application/json”);
var response=await client.PutAsync(apirl,httpContent);
var jsonResponseString=await response.Content.ReadAsStringAsync();
//填满
if(响应。IsSuccessStatusCode)
{
//反序列化
如果(!typeof(X).Equals(typeof(string)))
{
apiCallResult.ResponseObject=JsonConvert.DeserializeObject(jsonResponseString);
}
apiCallResult.IsError=false;
}
其他的
{
尝试
{
apErrorMessage myMessage=JsonConvert.DeserializeObject(jsonResponseString);
Sub Main(args As String())
    ProcessApi().Wait()
End Sub

Private Async Function ProcessApi() As Task(Of Boolean)
    Dim isRun As Boolean =  Await TestHelper.ProcessApi()
    Return isRun
End Function