HttpClient返回404找不到

时间:2018-07-09 08:04:52

标签: xamarin httpclient

我有一个xamarin应用程序,可从webAPI中提取数据。我检查了api地址很多次了,我确定它是正确的。当我调试代码时,我没有从服务器找到404错误。但是,当我将URL复制并粘贴到浏览器中时,得到了预期的结果。我不知道为什么我的应用返回404。

我的方法:

   public async Task<ICustomerType> GetById(int id)
    {
        string _token;

        if (App.Current.Properties.ContainsKey("token"))
        {
            _token = (string)App.Current.Properties["token"];
        }
        else
        { _token = null; }

        var webApiResponse =
            _connector.PostAsync(
                "api/Customer/get/id/" + id,
                string.Empty, _token).Result;

        var response = webApiResponse.Result.ToString();

        var jObjectResponse = JObject.Parse(response);

        ICustomerType customerTypeObj = null;

        return customerTypeObj;
    }

我到HttpClient的PostAsync方法的桥接方法:

    private async Task<TResponse> PostAsync(string requestPath, string 
jsonContent, bool getToken, string token)
    {
        HttpClient client = new HttpClient();

            client.BaseAddress = new Uri(_apiUrl);
            client.DefaultRequestHeaders.Accept.Clear();
            var contentType = new MediaTypeWithQualityHeaderValue("application/json");
            client.DefaultRequestHeaders.Accept.Add(contentType);

            if (getToken)
            {
                token =  GetApiTokenAsync().Result;
            }

            if (!string.IsNullOrEmpty(token))
            {
                client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
            }

            var httpContent = new StringContent(jsonContent, Encoding.UTF8, "application/json");

            var response = client.PostAsync(requestPath, httpContent).Result;
            var jsonData = await response.Content.ReadAsStringAsync();
            return JsonConvert.DeserializeObject<TResponse>(jsonData);

    }

令牌:正确

API网址:正确(我检查了调试输出中的“ /”符号。它们的位置正确。我的Api像这样:  https://MyApi.net/api/Personel/get/id/1

我的错误:

  
      
  • 响应{状态代码:404,原因短语:“未找到”,版本:1.1,内容:System.Net.Http.StreamContent,标头:{请求上下文:   appId = cid-v1:Some_String服务器:Kestrel
      严格的运输安全性:max-age = Some_Int Set-Cookie:   ARRAffinity = Some_String; Path = /; HttpOnly; Domain = MyDomain日期:星期一,   2018年7月9日7:54:19 GMT X-Powered-by:ASP.NET内容长度:0   }} System.Net.Http.HttpResponseMessage
  •   

1 个答案:

答案 0 :(得分:0)

您在API中的方法动词为“ GET”,但您在客户端中使用了“ POST”。因此在浏览器中可以使用,因为浏览器调用了“ GET”,但在客户端中却不起作用。

代替:

   var webApiResponse =
        _connector.PostAsync(
            "api/Customer/get/id/" + id,
            string.Empty, _token).Result;


使用:

   var webApiResponse =
        _connector.GetAsync(
            "api/Customer/get/id/" + id,
            string.Empty, _token).Result;
相关问题