ebashmakov
ebashmakov

Reputation: 649

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:

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.

Upvotes: 9

Views: 7217

Answers (1)

jgauffin
jgauffin

Reputation: 101150

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();
}

Upvotes: 14

Related Questions