【问题标题】:HttpClient Post CallHttpClient 发布调用
【发布时间】:2019-12-26 10:16:19
【问题描述】:

我想使用 HttpClient 进行 REST POST 调用。我一直有错误 - 'RestCall.PostRestCall(string, string, string, string)': 并非所有代码路径都返回值'

以下是我的代码。它的意思是接收baseUrl、contentType、requestBody、httpMethod;作为输入参数,返回响应状态码、状态描述和响应内容。

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace RestPostCall
{
    public class RestCall
    {
        public static string PostRestCall(string baseURL, string httpMethod, string contentType, string requestBody)
        {
            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri(baseURL);

            // Add an Accept header for JSON format.
            client.DefaultRequestHeaders.Accept.Add(new 
            MediaTypeWithQualityHeaderValue(contentType));

            // List data response.
            HttpResponseMessage response = client.GetAsync(requestBody).Result;
            if (response.IsSuccessStatusCode)
            {
                // Parse the response body.
                var dataObjects = response.Content.ReadAsAsync<IEnumerable<IDataObject>>().Result;  
                //Make sure to add a reference to System.Net.Http.Formatting.dll

            }
            else
            {
                Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
            }

            //Make any other calls using HttpClient here.

            //Dispose once all HttpClient calls are complete.
            client.Dispose();

         }
     }
 }

【问题讨论】:

  • return null;放在函数的末尾
  • 有什么原因你不能做这个方法async?使用.Result 是一个危险信号。

标签: c# rest post dotnet-httpclient


【解决方案1】:

你的方法没有返回任何值,所以更改签名返回void类型:

public static void PostRestCall(string baseURL, string httpMethod, string contentType, 
string requestBody)

【讨论】:

    【解决方案2】:

    将您的方法返回类型更改为 void,或者如果您想返回任何值,请使用 return 语句。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-26
      • 1970-01-01
      相关资源
      最近更新 更多