Referencing Web Api Locally from serperate MVC Application

本文关键字:serperate MVC Application from Locally Web Api Referencing | 更新日期: 2023-09-27 18:35:06

我有以下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。

现在我不确定我在这里做错了什么,所以如果有人能告诉我或给我一个简单的例子,我将不胜感激。

Referencing Web Api Locally from serperate MVC Application

您的问题是您的响应格式不正确。

在下面的代码中,您尝试用户响应。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;
        }
    }