2012-03-20 54 views
5

我ApiController與獲取動作是這樣的:的ASP.NET Web API:可選的Guid參數

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

我想,下面的請求是針對這個動作:

  • 的http:// {somedomain}/API /筆記用戶id = {GUID} & TAGID = {GUID}
  • HTTP:// {somedomain}/API /筆記用戶id = {GUID}
  • HTTP:// {somedomain}/api/notes?tagId = {Guid}

我應該怎樣做?

UPDATE:小心,api控制器不應該有沒有參數的另一個GET方法,或者你應該使用一個可選參數的動作。

回答

9

您需要使用空類型(IIRC,它可能與一個默認值(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(); 
} 
+0

由於工作,它的作品 – ebashmakov 2012-03-20 08:18:53