Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Web API: Optional Guid parameters

I have ApiController with Get action like this:

public IEnumerable<Note> Get(Guid userId, Guid tagId)
{
    var userNotes = _repository.Get(x => x.UserId == userId);
    var tagedNotes = _repository.Get(x => x.TagId == tagId);    

    return userNotes.Union(tagedNotes).Distinct();
}

I want that the following requests was directed to this action:

  • http://{somedomain}/api/notes?userId={Guid}&tagId={Guid}
  • http://{somedomain}/api/notes?userId={Guid}
  • http://{somedomain}/api/notes?tagId={Guid}

Which way should I do this?

UPDATE: Be careful, the api controller should not have another GET method without parameters or you should to use action with one optional parameter.

like image 969
ebashmakov Avatar asked Mar 20 '12 07:03

ebashmakov


1 Answers

You need to use Nullable type (IIRC, it might work with a default value (Guid.Empty)

public IEnumerable<Note> Get(Guid? userId = null, Guid? tagId = null)
{
    var userNotes = userId.HasValue ? _repository.Get(x => x.UserId == userId.Value) : new List<Note>();
    var tagNotes = tagId.HasValue ? _repository.Get(x => x.TagId == tagId.Value) : new List<Note>();
    return userNotes.Union(tagNotes).Distinct();
}
like image 136
jgauffin Avatar answered Oct 10 '22 03:10

jgauffin