我正在尝试获取“响应,序列化和使用”web api,我从未编写过web api代码。
我有以下Web API:
[HttpGet]
public IHttpActionResult SendMsg(string yourName)
{
var result = "Hi " + yourName;
if (result == null)
{
return NotFound();
}
return Ok(result);
}
我试图通过此代码获得响应:
private void ResponseWebAPI(string strApiAddress)
{
HttpWebRequest request = WebRequest.Create(strApiAddress) as HttpWebRequest;
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(response.GetResponseStream());
}
我收到的回复没有任何问题,但是当我加载回复时出现以下错误:
根级别的数据无效。第1行,第1位
答案 0 :(得分:1)
试试这个
private void ResponseWebAPI(string strApiAddress) {
var request = WebRequest.Create(strApiAddress) as HttpWebRequest;
var response = request.GetResponse() as HttpWebResponse;
using (Stream stream = response.GetResponseStream()) {
var reader = new StreamReader(stream, Encoding.UTF8);
var responseString = reader.ReadToEnd();
var xmlDoc = new XmlDocument();
xmlDoc.LoadXml(responseString);
}
}
答案 1 :(得分:1)
我已经尝试过您的代码了。
我建议您使用HttpClient
代替HttpWebRequest
,如下所示:
public async Task<Model> GetData(string url)
{
HttpClient httpClient = new HttpClient();
httpClient.BaseAddress = new Uri(url);
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage result = await httpClient.GetAsync(url);
if (result.IsSuccessStatusCode)
{
string contentResult = await result.Content.ReadAsStringAsync();
Model newModel = JsonConvert.DeserializeObject<Model>(contentResult);
}
return newModel;
}
答案 2 :(得分:1)
将请求Accept标头设置为application / json。
request.Accept = "application/json";
然后将响应作为JSON使用。
或者,您可以使用HttpClient,它具有更简单,更现代的API。
https://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client
public static async Task DoAsync()
{
var strApiAddress = "http://localhost";
HttpClient client = new HttpClient();
var str = await client.GetStringAsync(strApiAddress);
}
public static void Do()
{
var strApiAddress = "http://localhost";
HttpClient client = new HttpClient();
var str = client.GetStringAsync(strApiAddress).Result;
}