ASP.NET Web API:可选的Guid参数

eba*_*kov 7 c# asp.net guid asp.net-mvc-4 asp.net-web-api

我有ApiController和Get动作这样:

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();
}
Run Code Online (Sandbox Code Playgroud)

我希望以下请求针对此操作:

  • HTTP:// {somedomain}/API /笔记用户id = {GUID}&TAGID = {GUID}?
  • HTTP:// {somedomain}/API /笔记用户id = {GUID}?
  • HTTP:// {somedomain}/API /笔记TAGID = {GUID}?

我该怎么做?

更新:小心,api控制器不应该有没有参数的另一个GET方法,或者你应该使用一个可选参数的动作.

jga*_*fin 13

你需要使用Nullable类型(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();
}
Run Code Online (Sandbox Code Playgroud)