gpt4 book ai didi

c# - 返回 JSON 对象 (ASP.NET WebAPI)

转载 作者:IT老高 更新时间:2023-10-28 12:51:05 30 4
gpt4 key购买 nike

我有 ASP.NET Web API

它像这样返回 JSON

[{"CompanyID":1,"CompanyName":"Тест"},{"CompanyID":5,"CompanyName":"Фокстрот"}]

据我了解,这是 Json 数组,但我需要返回 JSOn Object 而不是它

像这样:{"results":[{"CompanyID":1,"CompanyName":"Тест"},{"CompanyID":5,"CompanyName":"Фокстрот"}]}

这是我的 GetCompanies Controller :

public class GetCompaniesController : ApiController
{
private ApplicationDbContext db = new ApplicationDbContext();

// GET: api/GetCompanies
public IQueryable<Companies> GetCompanies()
{
return db.Companies;
}

// GET: api/GetCompanies/5
[ResponseType(typeof(Companies))]
public async Task<IHttpActionResult> GetCompanies(int id)
{
Companies companies = await db.Companies.FindAsync(id);
if (companies == null)
{
return NotFound();
}

return Ok(companies);
}

// PUT: api/GetCompanies/5
[ResponseType(typeof(void))]
public async Task<IHttpActionResult> PutCompanies(int id, Companies companies)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}

if (id != companies.CompanyID)
{
return BadRequest();
}

db.Entry(companies).State = EntityState.Modified;

try
{
await db.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!CompaniesExists(id))
{
return NotFound();
}
else
{
throw;
}
}

return StatusCode(HttpStatusCode.NoContent);
}

// POST: api/GetCompanies
[ResponseType(typeof(Companies))]
public async Task<IHttpActionResult> PostCompanies(Companies companies)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}

db.Companies.Add(companies);
await db.SaveChangesAsync();

return CreatedAtRoute("DefaultApi", new { id = companies.CompanyID }, companies);
}

// DELETE: api/GetCompanies/5
[ResponseType(typeof(Companies))]
public async Task<IHttpActionResult> DeleteCompanies(int id)
{
Companies companies = await db.Companies.FindAsync(id);
if (companies == null)
{
return NotFound();
}

db.Companies.Remove(companies);
await db.SaveChangesAsync();

return Ok(companies);
}

protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}

private bool CompaniesExists(int id)
{
return db.Companies.Count(e => e.CompanyID == id) > 0;
}
}

我需要如何修改我的 Controller ?

谢谢

最佳答案

返回值时,试试这样:

public IHttpActionResult GetCompanies()
{
var companies = db.Companies.ToList();
return Ok( new { results = companies });
}

关于c# - 返回 JSON 对象 (ASP.NET WebAPI),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42566284/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com