我想使用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();
}
}
}
答案 0 :(得分:0)
您的方法未返回任何值,因此更改签名以返回void
类型:
public static void PostRestCall(string baseURL, string httpMethod, string contentType,
string requestBody)
答案 1 :(得分:0)
将方法的返回类型更改为void,或者如果要返回任何值,请使用return语句。