[英]Referencing Web Api Locally from serperate MVC Application
我有以下Web API
public class ApiTestController : ApiController
{
// GET api/<controller>
[HttpGet]
public string UploadImage(int id)
{
return "You entered = " + id;
}
}
運行時,我輸入/ api / ApiTest / 3它將擊中並返回您輸入了3
現在在單獨的MVC應用程序中,我嘗試通過執行以下操作來引用相同的api方法
private const string WebUrl = "http://localhost:1769/api/ApiTest/";
//
// GET: /Home/
public ActionResult Index()
{
try
{
var test = GetInvoiveNo(3);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
return View();
}
public string GetInvoiveNo(int id)
{
var uri = WebUrl + id;
using (var httpClient = new HttpClient())
{
Task response = httpClient.GetStringAsync(uri);
return JsonConvert.DeserializeObjectAsync<string>(response.ToString()).Result;
}
}
但是我得到了錯誤:
發生一個或多個錯誤
所以我看一下內部異常,它是這樣說的:
解析值時遇到意外字符:S.路徑”,行0,位置0。”}
現在我不確定在這里做錯了什么,所以如果有人可以告訴我或給我一個簡單的例子,我將不勝感激。
您的問題是您的回復格式不正確。
在下面的代碼中,您嘗試使用用戶response.ToString(),這是錯誤的,您必須使用用戶響應的結果。
public string GetInvoiveNo(int id)
{
var uri = WebUrl + id;
using (var httpClient = new HttpClient())
{
var response = httpClient.GetStringAsync(uri);
return JsonConvert.DeserializeObjectAsync<string>(response.Result).Result;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.