skip to Main Content

I am using the following code to call a post interface in Visual Studio 2022:

private List<Token> LoginToken(string username, string password)
{
 string api = "";
 List<Token> list = new List<Token>();
 string url = "";
 Dictionary<string, string> dics = new Dictionary<string, string>
 {
   { "username", username },
   { "password", password },
   { "loginType", "account" },
   { "grantType", "password" }
 };
 Task<string> task = Api.InvokeWebapi(url, api, "POST", dics);
 string result = task.Result;

 if (result != null)
 {
     JObject jsonObj = null;
     jsonObj = JObject.Parse(result);
     DataInfo info = new DataInfo();
     info.statusCode = Convert.ToInt32(jsonObj["code"]);
     info.message = jsonObj["message"].ToString();
     if (info.statusCode == 1)
     {
         JArray jlist = JArray.Parse(jsonObj["data"].ToString());
         for (int i = 0; i < jlist.Count; ++i)
         {
             Token ver = new Token();
             JObject tempo = JObject.Parse(jlist[i].ToString());
             ver.access_token = tempo["access_token"].ToString();
             ver.token_type = tempo["token_type"].ToString();
             ver.expires_in = Convert.ToInt32(tempo["expires_in"]);
             ver.scope = tempo["scope"].ToString();
             ver.name = tempo["name"].ToString();
             ver.my_Corp = tempo["my_Corp-Code"].ToString();
             ver.userId = Convert.ToInt32(tempo["userId"]);
             ver.username = tempo["username"].ToString();
             ver.jti = tempo["jti"].ToString();
             list.Add(ver);
         }
     }
 }
 return list;
}


public async Task<string> InvokeWebapi(string url, string api, string type, Dictionary<string, string> dics)
{
    string result = string.Empty;
    HttpClient client = new HttpClient();
    client.DefaultRequestHeaders.Add("Authorization", "Basic 1111");
    client.BaseAddress = new Uri(url);

    client.Timeout = TimeSpan.FromSeconds(510);

    if (type.ToLower() == "put")
    {
        HttpResponseMessage response;
        if (dics.Keys.Contains("input"))
        {
            if (dics != null)
            {
                foreach (var item in dics.Keys)
                {
                    api = api.Replace(item, dics[item]).Replace("{", "").Replace("}", "");
                }
            }
            var contents = new StringContent(dics["input"], Encoding.UTF8, "application/json");
            response = client.PutAsync(api, contents).Result;
            if (response.IsSuccessStatusCode)
            {
                result = await response.Content.ReadAsStringAsync();
                return result;
            }
            return result;
        }

        var content = new FormUrlEncodedContent(dics);
        response = client.PutAsync(api, content).Result;
        if (response.IsSuccessStatusCode)
        {
            result = await response.Content.ReadAsStringAsync();
            return result;
        }
    }
    else if (type.ToLower() == "post")
    {
        var content = new FormUrlEncodedContent(dics);

        HttpResponseMessage response = client.PostAsync(api, content).Result;
        if (response.IsSuccessStatusCode)
        {
            result = await response.Content.ReadAsStringAsync();
            return result;
        }
    }
    else if (type.ToLower() == "get")
    {
        HttpResponseMessage response = client.GetAsync(api).Result;

        if (response.IsSuccessStatusCode)
        {
            result = await response.Content.ReadAsStringAsync();
            return result;
        }
    }
    else
    {
        return result;
    }
    return result;
}
}

I am using the above code to call a post interface in Visual Studio 2022, but the error reported in jsonObj = JObject.Parse(result); is Newtonsoft.Json.JsonReaderException: "Error reading JObject from JsonReader. Path '', line 0, position 0."

Update:

I captured the response of the api when the error was reported:

{StatusCode: 415, ReasonPhrase: 'Unsupported Media Type', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Transfer-Encoding: chunked
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Pragma: no-cache
X-Frame-Options: DENY
Referrer-Policy: no-referrer
Cache-Control: no-store, must-revalidate, no-cache, max-age=0
Date: Wed, 17 Jul 2024 08:47:38 GMT
Server: nginx/1.24.0
Content-Type: application/json
Expires: 0
}}

2

Answers


  1. Chosen as BEST ANSWER

    Thanks to Panagiotis Kanavos and everyone for their suggestions for improvement. I will study them carefully later. My problem has been solved. The problem was that the format of SerializeObject(dics) was incorrect. I converted it later and it can run successfully.

    var json = JsonConvert.SerializeObject(dics);
    var content = new StringContent(json, Encoding.UTF8, "application/json");
    //var content = new FormUrlEncodedContent(dics);   Previous code
    

  2. The InvokeWebApi method is full of bugs, sends FORM content to a service that obviously expects JSON and hides errors, returning an empty string if something goes wrong. The remote service rejects the call due to the bad content but the calling code still tries to deserialize the empty string, resulting in the error.

    The real solution is to completely replace InvokeWebApi with the appropriate calls. First of all, HttpClient is thread-safe and meant to be reused. Creating a new one every time is a major bug, resulting in socket exhaustion.

    The HttpClient instance should be a field or parameter to the method. In ASP.NET Core the easiest way is to have it injected using DI. All it takes is a builder.Services.AddHttpClient() call, and adding HttpClient as a constructor parameter to the controller or service that needs it.

    builder.Services.AddHttpClient(client=>{
        client.DefaultRequestHeaders.Add("Authorization", "Basic 1111");
        client.BaseAddress = new Uri(siteUrl);
    });
    

    No matter where the HttpClient comes from, the entire LoginToken method can be simplified to this :

    async Task<List<Token>> LoginToken(string username, string password)
    {
        var request = new {
           username=username,
           password=password ,
           loginType="account",
           grantType="password"
        };
    
        var resp=await _client.PostAsJsonAsync(relativeUrl,request);
        if (!resp.IsSuccessStatusCode)
        {
            //Actually handle the problem, the application can't continue without a token
            _logger.LogError("Token call failed with {code}:{reason}",resp.StatusCode,resp.ReasonPhrase);
            throw new Exception(.....);
        }
        DataInfo info=await resp.Content.ReadAsJsonAsync<DataInfo>();
        if (info.Code == "0001") //Or whatever the success code is
        {
            return info.Data;
        }
        else 
        {
            _logger.LogError("Token retrieval failed with {code}:{message}",info.statusCode,info.message);
            //Actually do something about the error. 
            //The application can't proceed without a login token
        }
    }
    

    The PostAsJsonAsync method will serialize the request object directly to the request stream as JSON and make sure the correct content type is used.

    The code assumes the DataInfo and Token objects match the response JSON, as they should. For example :

    public class DataInfo
    {
        public int Code {get;set;}
        public string Message {get;set;}
        List<Token> Data{get;set;}
    }
    

    or

    public class DataInfo<T>
    {
        public int Code {get;set;}
        public string Message {get;set;}
        List<T> Data {get;set;}
    }
    

    The [JsonPropertyName("code")] attribute can be used to map code to a property named StatusCode

    public class DataInfo<T>
    {
        [JsonPropertyName("code")]
        public int StatusCode {get;set;}
        public string Message {get;set;}
        List<T> Data {get;set;}
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search