c# - net - visual studio web api json
Devolver objeto JSON(ASP.NET WebAPI) (1)
Tengo ASP.NET Web API
Me devuelve a JSON así.
[{"CompanyID":1,"CompanyName":"Тест"},{"CompanyID":5,"CompanyName":"Фокстрот"}]
Como entendí, esta es la matriz Json, pero necesito devolver el objeto JSOn en lugar de él
Así: {"results":[{"CompanyID":1,"CompanyName":"Тест"},{"CompanyID":5,"CompanyName":"Фокстрот"}]}
Aquí está mi controlador GetCompanies:
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;
}
}
¿Cómo necesito modificar mi controlador?
Gracias
Al devolver un valor, inténtalo de esta manera:
public IHttpActionResult GetCompanies()
{
var companies = db.Companies.ToList();
return Ok( new { results = companies });
}