Home > OS >  ASP.NET Core WebApi Return All Values by Attribute
ASP.NET Core WebApi Return All Values by Attribute

Time:03-09

My WebApi has a table for applications with the following class:

namespace Models.Public
{
    [Index(nameof(UUID), nameof(UID), IsUnique = true)]
    public class Application
    {
        public Application()
        {
            this.UUID = new Guid();
        }

        public int ID { get; set; }
        public Guid UUID { get; set; }
        [Required]
        public string UID { get; set; }
        public string Publisher { get; set; }
        public string Name { get; set; }
        public string Version { get; set; }
    }
}

The field UUID and ID are unique, so I was able to generate the required HttpGet command to obtain the results matching for that.

However, I am trying to obtain an IEnumerable object of all the items that match the Publisher field. That is, return all object that have "Google" as their Publisher.

My attempts have not been successful and I am hoping for some advise to fix my code:

// GET: api/Application/<publisher>
[HttpGet("{publisher}")]
public async Task<ActionResult<IEnumerable<Application>>> GetApplication(string publisher)
{
    var application = await _context.Application.ToListAsync(publisher);

    if (application == null)
    {
        return NotFound();
    }

    return await _context.Application.ToListAsync();
}

Publisher is not a unique value, so I'd like to be able to return all items as a JSON object that have whatever Publisher I type in the list. If no matches, error handle with NotFound();.

CodePudding user response:

You will need to filter using .Where, .Contains

// GET: api/Application/<publisher>
[HttpGet("{publisher}")]
public async Task<ActionResult<IEnumerable<ApplicationData>>> GetApplication(string publisher)
{
    var applications = _context.Application.Where(a=>a.Publisher.Contains(publisher)));

   /* You could also use == for exact match
      var applications = _context.Application.Where(a=>a.Publisher == publisher));
   */

    if (applications.Count() == 0)
    {
        return NotFound();
    }

    return await applications.ToListAsync();
}
  • Related