【发布时间】:2021-10-01 18:15:24
【问题描述】:
我在 CompanyInfoController 中有一个 async Task<ActionResult> 方法,我想在服务类 (ProductService) 中调用此方法。如何调用此方法并在服务方法中使用结果列表 (companyInfo)?
[HttpPost]
[Route("GetCompanyInfo")]
public async Task<ActionResult> GetCompanyInfo(List<int> companyId)
{
var section = this._configuration.GetSection("Company");
string uri = section.GetValue<string>("Host");
string endpoint = section.GetValue<string>("CompanyInfo");
using (var httpClient = new HttpClient())
{
string idContent = JsonConvert.SerializeObject(companyId);
httpClient.BaseAddress = new Uri(uri);
HttpResponseMessage responseMessage = await httpClient.PostAsync(endpoint, new StringContent(idContent, Encoding.UTF8, "application/json"));
if (responseMessage.IsSuccessStatusCode)
{
var content = await responseMessage.Content.ReadAsStringAsync();
var operationResult = JsonConvert.DeserializeObject<CompanyInfoResultJSON>(content);
var companyInfo = operationResult.CompanyInfo.SelectMany(x => x.CompanyInfoList).ToList();
return Ok(companyInfo);
}
else
{
return BadRequest();
}
}
}
我的ProductService:
public class ProductService : IProductService
{
private readonly DBContext _dbContext;
public ProductService(DBContext dbContext)
{
this._ dbContext = dbContext;
}
public IEnumerable<Products> GetCompanyProductList(List<int> companyId)
{
DateTime today = DateTime.Today;
var products =_ dbContext.Products.Where(x => x.ProductionDate < today).ToList();
foreach (item in companyId)
{
if (products.Any(x => x.companyId == item.companyId)
{
foreach (product in products)
{
products.CompanyName =??
// In here, I want to get the companyInfoList elements.
}
}
}
return products;
}
}
【问题讨论】:
-
你能发布产品服务吗?并指出您将在哪里使用该操作。我怀疑服务需要 ActionResult 方法。
-
@Serge 我将编辑帖子,我需要 companyInfo 列表来更新产品列表的某些行。
-
旁注.... 不要在
using块/语句中使用 HttpClient 并且不要丢弃它。互联网上有大量资源,因此解释了原因。 -
为什么不在控制器中依赖
IProductService,然后调用方法?
标签: c# asp.net-mvc entity-framework asp.net-core entity-framework-core