C# webapi call

Time:2022-1-19
//Httpclient calls help class
C# webapi callC# webapi call

public static class HttpRequestHelper
    {
        #Region get call
        /// 
        ///Asynchronous request using get method
        /// 
        ///Target link
        ///Returned string
        private async static Task GetResponseAsync(string url, Dictionary header = null, Dictionary parame = null)
        {
            try
            {
                HttpClient client = new HttpClient(new HttpClientHandler() { UseCookies = false });
                StringBuilder builder = new StringBuilder();
                builder.Append(url);
                if (header != null)
                {
                    client.DefaultRequestHeaders.Clear();
                    foreach (var item in header)
                    {
                        client.DefaultRequestHeaders.Add(item.Key, item.Value);
                    }
                }
                if (parame != null && parame.Count > 0)
                {
                    builder.Append("?");
                    int i = 0;
                    foreach (var item in parame)
                    {
                        if (i > 0)
                            builder.Append("&");
                        builder.AppendFormat("{0}={1}", item.Key, item.Value);
                        i++;
                    }
                }
                HttpResponseMessage response = await client.GetAsync(builder.ToString());
                response. EnsureSuccessStatusCode();// Used to throw exceptions

                return response;
            }
            catch (Exception e)
            {
                //If you want to throw an exception in the webapi, you must throw it like this, otherwise it throws an exception of 500 by default
                var resp = new HttpResponseMessage(HttpStatusCode.InternalServerError)
                {
                    Content = new StringContent(e.ToString()),
                    ReasonPhrase = "error"
                };
                throw new HttpResponseException(resp);
            }
        }

        public static async Task GetStringAsync(string url, Dictionary header = null, Dictionary parame = null)
        {
            var response = await GetResponseAsync(url, header, parame);
            return await response.Content.ReadAsStringAsync();
        }

        /// 
        ///Use get to return the list collection of asynchronous requests
        /// 
        ///  
        /// 
        public static async Task> GetListAsync(string url, Dictionary header = null, Dictionary parame = null)
        {
            var response = await GetResponseAsync(url, header, parame);
            return response.Content.ReadAsAsync>().Result;
        }

        #endregion

        #Region post call
        /// 
        ///Asynchronous request using post method
        /// 
        ///Target link
        ///Parameter string sent - JSON
        ///Returned string
        public static async Task PostAsync(string url, string json, Dictionary header = null, bool Gzip = false)
        {
            HttpClient client = new HttpClient(new HttpClientHandler() { UseCookies = false });
            HttpContent content = new StringContent(json);
            content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
            if (header != null)
            {
                client.DefaultRequestHeaders.Clear();
                foreach (var item in header)
                {
                    client.DefaultRequestHeaders.Add(item.Key, item.Value);
                }
            }
            HttpResponseMessage response = await client.PostAsync(url, content);
            response.EnsureSuccessStatusCode();
            string responseBody;
            if (Gzip)
            {
                GZipInputStream inputStream = new GZipInputStream(await response.Content.ReadAsStreamAsync());
                responseBody = new StreamReader(inputStream).ReadToEnd();
            }
            else
            {
                responseBody = await response.Content.ReadAsStringAsync();

            }
            return responseBody;
        }
        #endregion

        //Put and delete are the same 
    }

View Code

 

The same controller contains multiple API interfaces, which are implemented by specifying routes, as shown in the figure:

 

 

effect:

 

. NETCORE swagger is released to IIS, and the solution of 404 occurs when accessing the API

 

introduce
Using NETCORE as a pure back-end API has become more and more frequent, and swagger has become the choice of many people. Aspnetcore is usually restricted in code_ Close swagger when environment is production. But often when we need to publish the API to the local IIS for debugging or use by others, swagger will be prohibited. After publishing, the project often defaults to the production environment, which can be solved by modifying it to development.

 

resolvent
Open the web. EXE file published to the IIS folder Config file, add the following code:

Modified web The config structure is roughly as follows:

 

How to read appsetting in. Net core JSON configuration file

appsetting. JSON

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "Config": {
    "DbConnectionString": "Database=test;Data Source=127.0.0.1;User Id=root;Password=root;charset=utf8;pooling=true"
  }
} 

Write configuration file operation class

/// 
///Read appsetting configuration
/// 
public static class AppSetting
{
  private static IConfigurationSection _configurationSection = null;
  /// 
  ///Read configuration
  /// 
  /// 
  /// 
  public static string GetAppSetting(string key)
  {
      return _configurationSection.GetSection(key)?.Value;
  }
  /// 
  ///Set configuration
  /// 
  /// 
  public static void SetAppSetting(IConfigurationSection section)
  {
      _configurationSection = section;
  }
}

At startup CS in configureservices

public void ConfigureServices(IServiceCollection services)
{
  // ...
  //Set configuration
  AppSetting.SetAppSetting(Configuration.GetSection("Config"));
}

Use configuration

string connStr = AppSetting.GetAppSetting("PgConnectionString");

 

 

 

 

 

 

Links to related articles:

http://blog.itpub.net/28974745/viewspace-2761941/             

https://blog.csdn.net/gtosky4u/article/details/113886135                                                                                                                                                                                                                                                                                                 https://www.cnblogs.com/liuqiyun/p/9144816.html

https://blog.csdn.net/u011127019/article/details/53021164

(simple API interface creation tutorial)

https://www.jianshu.com/p/364f1842cae5

https://www.cnblogs.com/guohu/p/12982850.html     

Recommended Today

Modify user information changeinfo

When judging the persistence layer: Problem: there is such a problem when modifying user information. For example: the user’s email is not required. It was not empty originally. At this time, the user deletes the mailbox information and submits it. At this time, if it is not empty to judge whether it needs to be […]