2012-03-20 24 views
5

tengo ApiController con Get acción como esta:API Web ASP.NET: Opcional Guid parámetros

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

Quiero que las siguientes solicitudes se dirigen a esta acción:

  • http: // {} somedomain/api/notas de ID de usuario = {GUID} & TagId = {GUID}
  • http: // {somedomain}/api/notas de ID de usuario = {GUID}
  • http: // {} somedomain/api/notes? tagId = {Guid}

¿Qué camino debo hacer?

ACTUALIZACIÓN: Tenga cuidado, el controlador api no debe tener otro método GET sin parámetros o debe usar la acción con un parámetro opcional.

Respuesta

9

Es necesario utilizar el tipo anulable (IIRC, que podría funcionar con un valor por defecto (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

Gracias, es obra – ebashmakov