Lakshitha
Lakshitha

Reputation: 128

StatusCode: 422 - UnprocessableEntity Entity - HTTP Client .NET Core 5.0

I have the below code to make an HTTP request to an external endpoint, which throws me a 422 status code which is Unprocessable Entity. The same request payload works fine when directly invoked the external URL using Postman.

using (HttpClient httpClient = new HttpClient())
{
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            var Json = JsonConvert.SerializeObject(loanRequest, new JsonSerializerSettings
            {
                ContractResolver = new DefaultContractResolver
                {
                    IgnoreSerializableAttribute = false
                }
            });
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "externalEndPointURL");

            request.Content = new StringContent(Json,Encoding.UTF8,"application/json");//CONTENT-TYPE header
            HttpContent httpContent = new StringContent(Json, Encoding.UTF8, "application/json");
            httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            httpClient.DefaultRequestHeaders.TryAddWithoutValidation("content-type", "application/json; charset=utf-8");
            httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {token.AccessToken}");
            await httpClient.SendAsync(request).ContinueWith(task => {

                Console.WriteLine($"Response {task.Result}");
            });
}

//Request Pay load

{
    "Merchant": "GAP",
    "Lender": "BEN",
    "RateType": "VAR",
    "RepaymentType": "PI",
    "PropertyUsage": "INV",
    "CustomerRate": 0.0429,
    "LoanTerm": 20,
    "BorrowingAmount": 600000,
    "RateTerm": null
}

EDIT

Below is the comparison of the two request headers.

The working one Error

Upvotes: 2

Views: 10036

Answers (2)

Serge
Serge

Reputation: 43939

try this, if it is not working, nothing will be working

var baseUri= @"http://localhost:554";
var api = "/api/..";
    
using HttpClient client = new HttpClient { BaseAddress = new Uri(baseUri) };

client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
    
var json = JsonConvert.SerializeObject(loanRequest);    
    
var content = new StringContent(json, UTF8Encoding.UTF8, "application/json");

var response = await client.PostAsync(uri, content);

if (response.IsSuccessStatusCode)
{
    var stringData = await response.Content.ReadAsStringAsync();
    var result = JsonConvert.DeserializeObject<object>(stringData);
}

UPDATE

Json you posted has

"PropertyUsage": "INV",

but LoanRequestDTO doesn' t have this property. Since you are using an API Controller it automatically validates input and return an error immediatly, without trigering the action. I am wondering how this extra property could be created during serialization. Maybe you don't have some more properties ?

Upvotes: 1

Guru Stron
Guru Stron

Reputation: 143003

Check the headers postman sends (either by clicking "hidden" button in the headers tab for request or in the postman console after sending the request). Try adding ones which are missing from your request. Quite often sites are pretty nitpicky about User-Agent so I would start from that one first:

httpClient.DefaultRequestHeaders
    .TryAddWithoutValidation(HeaderNames.UserAgent,"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36")

P.S.

Also common consensus is that it is better to reuse HttpClient, so unless this is one off call - try to share the client between requests.

Upvotes: 0

Related Questions