英文:
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<Guid?> SchoolIds { get; set; }
 public List<Guid?> 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("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;
                }
            }
  }
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("application/json"));
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, "application/json");
var responseTask = client.PostAsync("http://localhost:6200/api/post_school_query", 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("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;
        }
    }
}
答案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("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;
        }
    }
}
答案3
得分: 0
这个对我来说可以工作。我还包括了一些更好的做法:
- 利用
async/await功能。不应该直接使用.Result。 - 不应该为每个请求创建
HttpClient。 
英文:
This one works for me. I've also included some better practices:
- Utilize 
async/awaitfunctionality. You shouldn't use.Resultdirectly. - You should not create a 
HttpClientper request. 
using System.Text;
using System.Text.Json;
using Microsoft.AspNetCore.Mvc;
namespace AspNetPlayground.Controllers;
[ApiController]
[Route("[controller]/[action]")]
public class TestController : ControllerBase
{
    private readonly HttpClient _httpClient;
    public TestController(IHttpClientFactory httpClientFactory) => _httpClient = httpClientFactory.CreateClient();
    [HttpPost]
    public Task<bool> IsNotNull([FromBody] SchoolQueryModel? schoolQueryModel) => Task.FromResult(schoolQueryModel is not null);
    [HttpPost]
    public async Task<bool> Run()
    {
        var getSchoolsModel = new SchoolQueryModel {SchoolIds = new() {Guid.NewGuid()}, DistrictIds = new() {Guid.NewGuid()}};
        using var requestContent = new StringContent(JsonSerializer.Serialize(getSchoolsModel), Encoding.UTF8, "application/json");
        using var response = await _httpClient.PostAsync("https://localhost:7041/Test/IsNotNull", requestContent);
        return response.IsSuccessStatusCode && await response.Content.ReadFromJsonAsync<bool>();
    }
}
public class SchoolQueryModel
{
    public List<Guid?> SchoolIds { get; init; } = new();
    public List<Guid?> 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);
                
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论