HttpClient POST响应未返回

huangapple go评论56阅读模式
英文:

HttpClient POST response is not returning

问题

I have created an http call to an API using httpclient. Request is sending to the end point but response is not receiving. No errors

public static async Task<List<BookingFeeResponseModel>> GetBookingFeeRuleDetailsAsync(string postData)
{
    try
    {
        HttpRequestMessage request = GetRequest(BOOKING_FEE_RULES_API_URL, postData, HttpMethod.Post);
        var response = await _httpClient.SendAsync(request, CancellationToken.None);

        if (response.IsSuccessStatusCode)
        {
            string responseContent = await response.Content.ReadAsStringAsync();
            var bookingFeeRules = JsonConvert.DeserializeObject<List<BookingFeeResponseModel>>(responseContent);
            return bookingFeeRules;
        }
    }
    catch (Exception ex)
    {
        Logger.Info($"Get Booking Fee Rule Details Err: {ex.Message}");
        throw;
    }
    return null;
}
private static HttpRequestMessage GetRequest(string apiUrl, string postData, HttpMethod httpMethod)
{
    var request = new HttpRequestMessage(httpMethod, apiUrl);
    request.Headers.Accept.Clear();
    request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    request.Headers.Add("altHost", ALT_HOST);
    if(httpMethod != HttpMethod.Get)
        request.Content = new StringContent(postData, Encoding.UTF8, "application/json");
    return request;
}

Here is the API which gets calling

[HttpPost]
public HttpResponseMessage GetBookingFeeAllRules([FromBody] BookingFeeRequestModel bookingFeeRequestModel)
{
    try
    {
        Logger.Info("Getting Booking Fee All Rules");
        var bookingFeeRules = new List<EditRuleModel>();
        var mappedBookingFeeRules = new List<BookingFeeResponseModel>();

        var allRules = GetAllRules();
        var ruleIdArray = allRules.Where(r => r.ApplyOrder > 1700 && r.ApplyOrder < 1800)?.Select(a => a.Id).ToArray();
        GetBookingFeeRuleDetails(bookingFeeRequestModel, bookingFeeRules, mappedBookingFeeRules, ruleIdArray, allRules);
        mappedBookingFeeRules = mappedBookingFeeRules.Where(r => r.RuleModels != null)?.ToList();
        var result = Request.CreateResponse(HttpStatusCode.OK, mappedBookingFeeRules);
        return result;
    }
    catch (Exception ex)
    {
        Logger.Info("Error getting booking fee disclaimer {0}", ex);
        throw;
    }
}

Can someone please help me with this.

I need to get the API response from GetBookingFeeAllRules. But now nothing is returning. Is I am doing anything wrong here?

英文:

I have created an http call to an API using httpclient. Request is sending to the end point but response is not receiving. No errors

public static async Task&lt;List&lt;BookingFeeResponseModel&gt;&gt; GetBookingFeeRuleDetailsAsync(string postData)
        {
            try
            {
                HttpRequestMessage request = GetRequest(BOOKING_FEE_RULES_API_URL, postData, HttpMethod.Post);
                var response = await _httpClient.SendAsync(request, CancellationToken.None);

                if (response.IsSuccessStatusCode)
                {
                    string responseContent = await response.Content.ReadAsStringAsync();
                    //JObject json = JObject.Parse(responseContent);

                    var bookingFeeRules = JsonConvert.DeserializeObject&lt;List&lt;BookingFeeResponseModel&gt;&gt;(responseContent);
                    return bookingFeeRules;
                }
            }
            catch (Exception ex)
            {
                Logger.Info($&quot;Get Booking Fee Rule Details Err: {ex.Message}&quot;);
                throw;
            }
            return null;
        }
private static HttpRequestMessage GetRequest(string apiUrl, string postData, HttpMethod httpMethod)
        {
            var request = new HttpRequestMessage(httpMethod, apiUrl);
            request.Headers.Accept.Clear();
            request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(&quot;application/json&quot;));
            request.Headers.Add(&quot;altHost&quot;, ALT_HOST);
            if(httpMethod != HttpMethod.Get)
                request.Content = new StringContent(postData, Encoding.UTF8, &quot;application/json&quot;);
            return request;
        }

Here is the API which gets calling

        [HttpPost]
        public HttpResponseMessage GetBookingFeeAllRules([FromBody] BookingFeeRequestModel bookingFeeRequestModel)
        {
            try
            {
                Logger.Info(&quot;Getting Booking Fee All Rules&quot;);
                var bookingFeeRules = new List&lt;EditRuleModel&gt;();
                var mappedBookingFeeRules = new List&lt;BookingFeeResponseModel&gt;();

                var allRules = GetAllRules();
                var ruleIdArray = allRules.Where(r =&gt; r.ApplyOrder &gt; 1700 &amp;&amp; r.ApplyOrder &lt; 1800)?.Select(a =&gt; a.Id).ToArray();
                GetBookingFeeRuleDetails(bookingFeeRequestModel, bookingFeeRules, mappedBookingFeeRules, ruleIdArray, allRules);
                mappedBookingFeeRules = mappedBookingFeeRules.Where(r =&gt; r.RuleModels != null)?.ToList();
                var result = Request.CreateResponse(HttpStatusCode.OK, mappedBookingFeeRules);
                return result;
            }
            catch (Exception ex)
            {
                Logger.Info(&quot;Error getting booking fee disclaimer {0}&quot;, ex);
                throw;
            }
        }

Can someone please help me with this.

I need to get the API response from GetBookingFeeAllRules. But now nothing is returning.
Is I am doing anything wrong here?

答案1

得分: 0

你没有提供一些方法和模型,所以我根据你的逻辑构建了一个简单的示例,你可以参考它。

模型:

public class BookingFeeResponseModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    public RuleModel RuleModels { get; set; }
}

public class BookingFeeRequestModel
{
    public string postData { get; set; }
}

public class EditRuleModel
{
    public int Id { get; set; }
}

public class RuleModel
{
    public int Id { get; set; }
    public int ApplyOrder { get; set; }
}

GetBookingFeeRuleDetailsAsync方法:

[HttpPost]
public async Task<List<BookingFeeResponseModel>> GetBookingFeeRuleDetailsAsync(string postData)
{
    try
    {
        HttpClient _httpClient = new HttpClient();
        HttpRequestMessage request = GetRequest("https://localhost:7247/api/Response", postData, HttpMethod.Post);
                   
        var response = await _httpClient.SendAsync(request, CancellationToken.None);

        var ResultDetail = response.Content.ReadAsStringAsync().Result;

        if (response.IsSuccessStatusCode)
        {
            string responseContent = await response.Content.ReadAsStringAsync();
            var bookingFeeRules = JsonConvert.DeserializeObject<List<BookingFeeResponseModel>>(responseContent);
            return bookingFeeRules;
        }
    }
    catch (Exception ex)
    {
        throw;
    }
    return null;
}

private static HttpRequestMessage GetRequest(string apiUrl, string postData, HttpMethod httpMethod)
{
    var request = new HttpRequestMessage(httpMethod, apiUrl);
    request.Headers.Accept.Clear();
    request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    request.Headers.Add("altHost", "ALT_HOST");
    BookingFeeRequestModel bookingFeeRequestModel = new BookingFeeRequestModel() { postData = postData };
    if (httpMethod != HttpMethod.Get)
        request.Content = new StringContent(JsonConvert.SerializeObject(bookingFeeRequestModel), Encoding.UTF8, "application/json");
    return request;
}

CreateResponse扩展方法:

public static IActionResult CreateResponse(this HttpRequest request, int status, object content)
{
    return new ObjectResult(content)
    {
        StatusCode = status
    };
}

GetBookingFeeAllRules方法:

[HttpPost]
public IActionResult GetBookingFeeAllRules([FromBody] BookingFeeRequestModel bookingFeeRequestModel)
{
    try
    {
        var bookingFeeRules = new List<EditRuleModel>();
        var mappedBookingFeeRules = new List<BookingFeeResponseModel>()
        { 
            new BookingFeeResponseModel(){ Id=1,Name = "Name1",RuleModels = new RuleModel(){ Id = 1,ApplyOrder = 1701} },
            new BookingFeeResponseModel(){ Id=2,Name = "Name2",RuleModels = new RuleModel(){ Id = 2,ApplyOrder = 1801} },
            new BookingFeeResponseModel(){ Id=3,Name = "Name3",RuleModels = new RuleModel(){ Id = 3,ApplyOrder = 1702} },
            new BookingFeeResponseModel(){ Id=4,Name = "Name4",RuleModels = new RuleModel(){ Id = 4,ApplyOrder = 1802} },
        };

        var allRules = GetAllRules();
        var ruleIdArray = allRules.Where(r => r.ApplyOrder > 1700 && r.ApplyOrder < 1800)?.Select(a => a.Id).ToArray();
        mappedBookingFeeRules = mappedBookingFeeRules.Where(r => r.RuleModels != null)?.ToList();
                
        var result = Request.CreateResponse(200, mappedBookingFeeRules);
        return result;
    }
    catch (Exception ex)
    { 
        throw;
    }
}

private List<RuleModel> GetAllRules()
{
    List<RuleModel> ruleModel = new List<RuleModel>()
    {
        new RuleModel(){ Id = 1,ApplyOrder = 1701},
        new RuleModel(){ Id = 2,ApplyOrder = 1801},
        new RuleModel(){ Id = 3,ApplyOrder = 1702},
        new RuleModel(){ Id = 4,ApplyOrder = 1802},
    };
    return ruleModel;
}

希望这能帮助你。

英文:

You have not provided some methods and models, so I built a simple example based on your logic, you can refer to it.

Model:

public class BookingFeeResponseModel
{ 
    public int Id { get; set; }
    public string Name { get; set; }
    public RuleModel RuleModels { get; set; }
}

public class BookingFeeRequestModel
{ 
    public string postData { get;set; }
}

public class EditRuleModel
{ 
    public int Id { get; set; }
}

public class RuleModel
{ 
    public int Id { get; set; }
    public int ApplyOrder { get; set; }
}

GetBookingFeeRuleDetailsAsync:

[HttpPost]
public async Task&lt;List&lt;BookingFeeResponseModel&gt;&gt; GetBookingFeeRuleDetailsAsync(string postData)
{
    try
    {
        HttpClient _httpClient = new HttpClient();
        HttpRequestMessage request = GetRequest(&quot;https://localhost:7247/api/Response&quot;, postData, HttpMethod.Post);
               
        var response = await _httpClient.SendAsync(request, CancellationToken.None);

        var ResultDetail = response.Content.ReadAsStringAsync().Result;

        if (response.IsSuccessStatusCode)
        {
            string responseContent = await response.Content.ReadAsStringAsync();
            //JObject json = JObject.Parse(responseContent);

            var bookingFeeRules = JsonConvert.DeserializeObject&lt;List&lt;BookingFeeResponseModel&gt;&gt;(responseContent);
            return bookingFeeRules;
        }
    }
    catch (Exception ex)
    {
        throw;
    }
    return null;
}
private static HttpRequestMessage GetRequest(string apiUrl, string postData, HttpMethod httpMethod)
{
    var request = new HttpRequestMessage(httpMethod, apiUrl);
    request.Headers.Accept.Clear();
    request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(&quot;application/json&quot;));
    request.Headers.Add(&quot;altHost&quot;, &quot;ALT_HOST&quot;);
    BookingFeeRequestModel bookingFeeRequestModel = new BookingFeeRequestModel() { postData = postData };
    if (httpMethod != HttpMethod.Get)
        request.Content = new StringContent(JsonConvert.SerializeObject(bookingFeeRequestModel), Encoding.UTF8, &quot;application/json&quot;);
    return request;
}

In the GetRequest method, I use JsonConvert.SerializeObject(bookingFeeRequestModel) to replace postData, otherwise I will receive Bad Request and cannot enter GetBookingFeeAllRules. You can add breakpoints to see if you successfully get inside GetBookingFeeAllRules.

Also, you can add var ResultDetail = response.Content.ReadAsStringAsync().Result; before if (response.IsSuccessStatusCode) to see if there is an error message.

CreateResponse extension method:

public static IActionResult CreateResponse(this HttpRequest request, int status, object content)
{
    return new ObjectResult(content)
    {
        StatusCode = status
     };
}

GetBookingFeeAllRules:

[HttpPost]
public IActionResult GetBookingFeeAllRules([FromBody] BookingFeeRequestModel bookingFeeRequestModel)
{
    try
    {
        var bookingFeeRules = new List&lt;EditRuleModel&gt;();
        var mappedBookingFeeRules = new List&lt;BookingFeeResponseModel&gt;()
        { 
            new BookingFeeResponseModel(){ Id=1,Name = &quot;Name1&quot;,RuleModels = new RuleModel(){ Id = 1,ApplyOrder = 1701} },
            new BookingFeeResponseModel(){ Id=2,Name = &quot;Name2&quot;,RuleModels = new RuleModel(){ Id = 2,ApplyOrder = 1801} },
            new BookingFeeResponseModel(){ Id=3,Name = &quot;Name3&quot;,RuleModels = new RuleModel(){ Id = 3,ApplyOrder = 1702} },
            new BookingFeeResponseModel(){ Id=4,Name = &quot;Name4&quot;,RuleModels = new RuleModel(){ Id = 4,ApplyOrder = 1802} },
        };

        var allRules = GetAllRules();
        var ruleIdArray = allRules.Where(r =&gt; r.ApplyOrder &gt; 1700 &amp;&amp; r.ApplyOrder &lt; 1800)?.Select(a =&gt; a.Id).ToArray();
        //GetBookingFeeRuleDetails(bookingFeeRequestModel, bookingFeeRules, mappedBookingFeeRules, ruleIdArray, allRules);
        mappedBookingFeeRules = mappedBookingFeeRules.Where(r =&gt; r.RuleModels != null)?.ToList();
                
        var result = Request.CreateResponse(200, mappedBookingFeeRules);
        return result;
    }
    catch (Exception ex)
    { 
        throw;
    }
}

private List&lt;RuleModel&gt; GetAllRules()
{
    List&lt;RuleModel&gt; ruleModel = new List&lt;RuleModel&gt;()
    {
        new RuleModel(){ Id = 1,ApplyOrder = 1701},
        new RuleModel(){ Id = 2,ApplyOrder = 1801},
        new RuleModel(){ Id = 3,ApplyOrder = 1702},
        new RuleModel(){ Id = 4,ApplyOrder = 1802},
    };
    return ruleModel;
}

You can first check whether the breakpoint of the called Api is hit, and then check whether the parameters can be received:
HttpClient POST响应未返回

If there is no problem, you can debug step by step to ensure that there is no problem with each step:
HttpClient POST响应未返回

If this breakpoint is not hit, you can view the corresponding error message to find out what the problem is:
HttpClient POST响应未返回

If you don't find the problem, you can call your Api interface through Postman to see if the result is returned as you expected.

Hope this can help you.

huangapple
  • 本文由 发表于 2023年3月31日 23:51:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/75900477.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定