To give some background on this particular code, there is a controller which recieves an object, hashes parts of it and looks into a database to see if there is a similar hash in the db, if there is, it returns a stored result back to the caller.

If a stored hash match isnt found, the current environment is resolved and based on the current environment, the the object is passed on to another api.

When the second api responds, the result is stored in a hash in the Database and the result is also returned to a caller.

public async Task<IActionResult> SubmithistoryRequestAsync([FromBody] IncominghistoryRequest dtohistoryRequest)
    var responseContent = "";
    string hash = "";

    //Build Hashable String
    string hashableStr = dtohistoryRequest.historyInquiryRequest.custFirstName +
                         dtohistoryRequest.historyInquiryRequest.custLastName +
                         dtohistoryRequest.historyInquiryRequest.previousGameScore +

    hash = EncryptionExtension.Hash(hashableStr);

    //If not specifically ignored cache, return history request from cache
    if (dtohistoryRequest.historyInquiryRequest.ignoreCache != true)
        //Check if Hash Exists
        var results = _interconnectCodesRepository.ChecktexQuery(hash);

        if (results != null)
            //Data exists
            //Return Cached Response
            //with json attribute
            StringBuilder builder = new StringBuilder(results.texresponseHash);
            int averageHistorye =Convert.ToInt32( results.averageHistorye);
            builder.Replace(" \"isCachedResponse\": false,", " \"averageHistorye\": "+ averageHistorye +",\"isCachedResponse\": true,");
            string retVal = builder.ToString();

            return this.Content(retVal, "application/json");


    // Serialize our concrete class into a JSON String
    var stringPayload = await Task.Run(() => JsonConvert.SerializeObject(dtohistoryRequest));

    // Wrap our JSON inside a StringContent which then can be used by the HttpClient class
    var httpContent = new StringContent(stringPayload, Encoding.UTF8, "application/json");

    using (var httpClient = new HttpClient())

        // Add an Accept header for JSON format.
        httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        httpClient.DefaultRequestHeaders.Authorization =

        //Fetch Current Environment Type
        var envRaw = Environment.GetEnvironmentVariable("apiEnv");
        texApiUrls.EnvironmentType env;
        if (!Enum.TryParse(envRaw, out env))
            return BadRequest("Invalid environment provided in environment variable apiEnv: " + envRaw);

        // Formatted and Resolved URL
        var apiUrl = texApiUrls.GettexApiUrlBasedOnEnvironment(env, texApiUrls.ApiType.historyInquiry);

        // Do the actual request and await the response
        var httpResponse =
            await httpClient.PostAsync(apiUrl, httpContent);

        // If the response contains content we want to read it!
        if (httpResponse.Content != null)
            responseContent = await httpResponse.Content.ReadAsStringAsync();

            // From here on you could deserialize the ResponseContent back again to a concrete C# type using Json.Net
            // Serialize our concrete class into a JSON String
            int averageHistorye = GetaverageHistorye(responseContent);
            responseContent = responseContent.Insert(2, "\"averageHistorye\": " + averageHistorye + ", \"isCachedResponse\": false,");

            //Save to Database
            //Only if a Median Score was returned
            if (averageHistorye > 0)
                //Map objects
                var texquery = new texquery();
                texquery.UpdatedDate = DateTime.Now;
                texquery.CustomerDetailsHash = hash;
                texquery.texresponseHash = responseContent.RemoveLineEndings();
                texquery.averageHistorye = averageHistorye.ToString();
            return this.Content(responseContent, "application/json");

    //Else ? NLog To the Rescue
    return BadRequest("Interconnect Api has encountered an internal error");

public int GetaverageHistorye(string response)
        var result = JsonConvert.DeserializeObject<historyResponseDto.texhistoryResponse>(response);
        string decision = result.historyInquiryResponse.decisionText;
        return _interconnectCodesRepository.GetaverageHistorye(decision);
    catch (Exception)
        return 0;

I believe this code can be refactored quite a bit because of all the swiss army knife type stuff it is doing. But I am not sure what all items are prime candidates for refactoring. Any other performance or code optimization suggestion is very welcome.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.