C# WebApi 調用


//HttpClient調用幫助類
  public static class HttpRequestHelper
    {
        #region Get調用
        /// <summary>
        /// 使用get方法異步請求
        /// </summary>
        /// <param name="url">目標鏈接</param>
        /// <returns>返回的字符串</returns>
        private async static Task<HttpResponseMessage> GetResponseAsync(string url, Dictionary<string, string> header = null, Dictionary<string, string> 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();//用來拋異常的

                return response;
            }
            catch (Exception e)
            {
                //在webapi中要想拋出異常必須這樣拋出,否則之拋出一個默認500的異常
                var resp = new HttpResponseMessage(HttpStatusCode.InternalServerError)
                {
                    Content = new StringContent(e.ToString()),
                    ReasonPhrase = "error"
                };
                throw new HttpResponseException(resp);
            }
        }

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

        /// <summary>
        /// 使用Get返回異步請求返回List集合
        /// </summary>
        /// <typeparam name="T"></typeparam> 
        /// <returns></returns>
        public static async Task<List<T>> GetListAsync<T>(string url, Dictionary<string, string> header = null, Dictionary<string, string> parame = null)
        {
            var response = await GetResponseAsync(url, header, parame);
            return response.Content.ReadAsAsync<List<T>>().Result;
        }

        #endregion

        #region Post調用
        /// <summary>
        /// 使用post方法異步請求
        /// </summary>
        /// <param name="url">目標鏈接</param>
        /// <param name="json">發送的參數字符串-json</param>
        /// <returns>返回的字符串</returns>
        public static async Task<string> PostAsync(string url, string json, Dictionary<string, string> 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、Delete方式相同 
    }
View Code

 

 同一控制器包含多個API接口,通過指定路由實現,如圖:

 

 

 效果:

 

 .NetCore swagger發布到iis時訪問api出現404的解決方案

 

介紹
使用netcore作為純后端提供api已經變得越來越頻繁,swagger也成為很多人的選擇。通常會在代碼中限制ASPNETCORE_ENVIRONMENT為Production時關閉swagger。但是往往我們需要將api發布到本地iis調試或供他人使用時,swagger將會被禁止。發布后項目往往默認為Production環境,將其修改為Development即可解決。

 

解決方法
打開發布到iis的文件夾下的web.config文件,添加以下代碼:

<environmentVariables>
<environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Development" />
</environmentVariables>

修改后的web.config結構大致如下:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
<location path="." inheritInChildApplications="false">
<system.webServer>
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
</handlers>
<aspNetCore processPath="dotnet" arguments="*.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" hostingModel="InProcess">
<environmentVariables>
<environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Development" />
</environmentVariables>
</aspNetCore>
</system.webServer>
</location>
</configuration>
<!--ProjectGuid: 15af0485-b65a-422a-bf12-5877b85abb6c-->

 

.NET Core中如何讀取appsetting.json配置文件

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"
  }
} 

編寫配置文件操作類

/// <summary>
/// 讀取appsetting配置
/// </summary>
public static class AppSetting
{
  private static IConfigurationSection _configurationSection = null;
  /// <summary>
  /// 讀取配置
  /// </summary>
  /// <param name="key"></param>
  /// <returns></returns>
  public static string GetAppSetting(string key)
  {
      return _configurationSection.GetSection(key)?.Value;
  }
  /// <summary>
  /// 設置配置
  /// </summary>
  /// <param name="section"></param>
  public static void SetAppSetting(IConfigurationSection section)
  {
      _configurationSection = section;
  }
}

在Startup.cs的ConfigureServices中設置配置

public void ConfigureServices(IServiceCollection services)
{
  // ...
  // 設置配置
  AppSetting.SetAppSetting(Configuration.GetSection("Config"));
}

使用配置

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

 

 

 

 

 

 

相關文章鏈接 :     

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

(簡單API接口創建教程)

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

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM