9

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.

1 Answer 1

14

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();
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.