【发布时间】: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