如何在 .Net Core 中使用请求对象调用一个端点。

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

How to call a endpoint in .Net core with request object

问题

以下是您提供的代码的中文翻译部分:

// 在Api 1中,我有一个如下所示的端点
[HttpPost]
public ActionResult PostSchoolQuery([FromBody] SchoolQueryModel schoolQueryModel, [FromHeader] string authorization)
{

}

// 这里是请求模型类的定义
public class SchoolQueryModel
{
 public List<Guid?> SchoolIds { get; set; }
 public List<Guid?> DistrictIds { get; set; }
}

// 当我尝试从Api 2中调用PostSchoolQuery端点时,Api 1中始终接收到空值
public ActionResult GetUserSchools(SchoolQueryModel getSchoolsModel)
{
   dynamic schoolDetails = null;          
    var requestContent = new JsonSerializer.Serialize(getSchoolsModel);
    using (var client = new HttpClient())
    {
        client.DefaultRequestHeaders.Add("Authorization", _infrastructureAuthKey);
        var responseTask = client.PostAsync("http://localhost:6200/api/post_school_query", requestContent);
        if (responseTask.Result.IsSuccessStatusCode)
        {
            var readTask = responseTask.Result.Content.ReadAsAsync<JObject>();
            readTask.Wait();
            schoolDetails = readTask.Result;
        }
    }
}

请告诉我如何修复,谢谢。
英文:

I've a endpoint like below in Api 1

[HttpPost]
public ActionResult PostSchoolQuery([FromBody] SchoolQueryModel schoolQueryModel, [FromHeader] string authorization)
{

}

Here the Request Model class like below

public class SchoolQueryModel
{
 public List&lt;Guid?&gt; SchoolIds { get; set; }
 public List&lt;Guid?&gt; DistrictIds { get; set; }
}

And when I try to call the endpoint PostSchoolQuery from Api 2 like below , In api-1 I'm always receiving null values

 public ActionResult GetUserSchools(SchoolQueryModel getSchoolsModel)
        {
           dynamic schoolDetails = null;          
            var requestContent = new JsonSerializer.Serialize(getSchoolsModel);
            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Add(&quot;Authorization&quot;, _infrastructureAuthKey);
                var responseTask = client.PostAsync(&quot;http://localhost:6200/api/post_school_query&quot;, requestContent);
                if (responseTask.Result.IsSuccessStatusCode)
                {
                    var readTask = responseTask.Result.Content.ReadAsAsync&lt;JObject&gt;();
                    readTask.Wait();
                    schoolDetails = readTask.Result;
                }
            }
  }

let me know for a fix, Thanks

答案1

得分: 1

首先尝试在从Api 2发出请求时将Content-Type标头设置为"application/json":

client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

然后,您需要从序列化的请求主体创建一个StringContent对象,并将其作为PostAsync方法的第二个参数传递。您可以按照以下方式执行此操作:

var content = new StringContent(requestContent, Encoding.UTF8, "application/json");
var responseTask = client.PostAsync("http://localhost:6200/api/post_school_query", content);

因此,您的GetUserSchools方法应该如下所示:

public ActionResult GetUserSchools(SchoolQueryModel getSchoolsModel)
{
   dynamic schoolDetails = null;          
    var requestContent = new JsonSerializer.Serialize(getSchoolsModel);
    using (var client = new HttpClient())
    {
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        client.DefaultRequestHeaders.Add("Authorization", _infrastructureAuthKey);
        var content = new StringContent(requestContent, Encoding.UTF8, "application/json");
        var responseTask = client.PostAsync("http://localhost:6200/api/post_school_query", content);
        if (responseTask.Result.IsSuccessStatusCode)
        {
            var readTask = responseTask.Result.Content.ReadAsAsync<JObject>();
            readTask.Wait();
            schoolDetails = readTask.Result;
        }
    }
}
英文:

First try to set the Content-Type header to "application/json" when making the request from Api 2:

client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(&quot;application/json&quot;));

Then you need to create a StringContent object from the serialized request body, and pass it as the second argument to the PostAsync method. You can do this as follows:

var content = new StringContent(requestContent, Encoding.UTF8, &quot;application/json&quot;);
var responseTask = client.PostAsync(&quot;http://localhost:6200/api/post_school_query&quot;, content);

So your GetUserSchools method should look like:

public ActionResult GetUserSchools(SchoolQueryModel getSchoolsModel)
{
   dynamic schoolDetails = null;          
    var requestContent = new JsonSerializer.Serialize(getSchoolsModel);
    using (var client = new HttpClient())
    {
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(&quot;application/json&quot;));
        client.DefaultRequestHeaders.Add(&quot;Authorization&quot;, _infrastructureAuthKey);
        var content = new StringContent(requestContent, Encoding.UTF8, &quot;application/json&quot;);
        var responseTask = client.PostAsync(&quot;http://localhost:6200/api/post_school_query&quot;, content);
        if (responseTask.Result.IsSuccessStatusCode)
        {
            var readTask = responseTask.Result.Content.ReadAsAsync&lt;JObject&gt;();
            readTask.Wait();
            schoolDetails = readTask.Result;
        }
    }
}

答案2

得分: 0

尝试这个 PostAsJsonAsync

public ActionResult GetUserSchools(SchoolQueryModel getSchoolsModel)
{
    dynamic schoolDetails = null;

    using (var client = new HttpClient())
    {
        client.DefaultRequestHeaders.Add("Authorization", _infrastructureAuthKey);
        var responseTask = client.PostAsJsonAsync("http://localhost:6200/api/post_school_query", getSchoolsModel);
        if (responseTask.Result.IsSuccessStatusCode)
        {
            var readTask = responseTask.Result.Content.ReadAsAsync<JObject>();
            readTask.Wait();
            schoolDetails = readTask.Result;
        }
    }
}
英文:

Try this one PostAsJsonAsync

public ActionResult GetUserSchools(SchoolQueryModel getSchoolsModel)
{
    dynamic schoolDetails = null;

    using (var client = new HttpClient())
    {
        client.DefaultRequestHeaders.Add(&quot;Authorization&quot;, _infrastructureAuthKey);
        var responseTask = client.PostAsJsonAsync(&quot;http://localhost:6200/api/post_school_query&quot;, getSchoolsModel);
        if (responseTask.Result.IsSuccessStatusCode)
        {
            var readTask = responseTask.Result.Content.ReadAsAsync&lt;JObject&gt;();
            readTask.Wait();
            schoolDetails = readTask.Result;
        }
    }
}

答案3

得分: 0

这个对我来说可以工作。我还包括了一些更好的做法:

英文:

This one works for me. I've also included some better practices:

using System.Text;
using System.Text.Json;
using Microsoft.AspNetCore.Mvc;

namespace AspNetPlayground.Controllers;

[ApiController]
[Route(&quot;[controller]/[action]&quot;)]
public class TestController : ControllerBase
{
    private readonly HttpClient _httpClient;

    public TestController(IHttpClientFactory httpClientFactory) =&gt; _httpClient = httpClientFactory.CreateClient();

    [HttpPost]
    public Task&lt;bool&gt; IsNotNull([FromBody] SchoolQueryModel? schoolQueryModel) =&gt; Task.FromResult(schoolQueryModel is not null);

    [HttpPost]
    public async Task&lt;bool&gt; Run()
    {
        var getSchoolsModel = new SchoolQueryModel {SchoolIds = new() {Guid.NewGuid()}, DistrictIds = new() {Guid.NewGuid()}};
        using var requestContent = new StringContent(JsonSerializer.Serialize(getSchoolsModel), Encoding.UTF8, &quot;application/json&quot;);
        using var response = await _httpClient.PostAsync(&quot;https://localhost:7041/Test/IsNotNull&quot;, requestContent);
        return response.IsSuccessStatusCode &amp;&amp; await response.Content.ReadFromJsonAsync&lt;bool&gt;();
    }
}

public class SchoolQueryModel
{
    public List&lt;Guid?&gt; SchoolIds { get; init; } = new();
    public List&lt;Guid?&gt; DistrictIds { get; init; } = new();
}

答案4

得分: 0

这个修复对我有效,我不确定为什么。如果有人知道,请在这里评论。

在我的api -2中,我使用JObject而不是请求模型,直接使用PostAsJsonAsync。

public ActionResult GetUserSchools(JObject getSchoolsModel)
{
    using (var client = new HttpClient())
    {
        var responseTask = await client.PostAsJsonAsync(requestUrl, getSchoolsModel);
    }
}
英文:

This fix works for me , I'm not sure why. if anyone knows please comment here

In my api -2 I used JObject instead of a request model and PostAsJsonAsync directly

public ActionResult GetUserSchools(JObject getSchoolsModel)
{
using (var client = new HttpClient())
{
               
var responseTask = await client.PostAsJsonAsync( requestUrl, getSchoolsModel);
                
}

}

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

发表评论

匿名网友

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

确定