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

时间:2022-03-28 11:02:14

I have ApiController with Get action like this:

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

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.

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

1 个解决方案

#1


11  

You need to use Nullable type (IIRC, it might work with a default value (Guid.Empty)

你需要使用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();
}

#1


11  

You need to use Nullable type (IIRC, it might work with a default value (Guid.Empty)

你需要使用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();
}