我正在尝试查询“ UserType”对象,并获取属性“ name”
因此,整个JSON对象为User:,并且api调用应如下所示:
api/user?userTypeName=randomUserTypeName
我可以在其中搜索特定的userTypeName并返回名称。
API调用:
在这里,我要使用FromQuery,以便能够搜索userTypeName并检查userTypeName是否等于输入的名称。
// GET: /api/User/userTypeName
[HttpGet("{userTypeName}")]
public async Task<ActionResult<IEnumerable<User>>> GetAsync(([FromQuery(Name = "userTypeName")]string userTypeName) {
var result = await ctx.User
.Include(x => x.UserType)
.Where(x => x.UserType.Name.ToLower() == UserTypeName.ToLower())
.ToListAsync();
if (result == null) return BadRequest();
return result;
}
对象看起来像这样:
{
"id": 9,
"userTypeId": 1,
"userType": {
"id": 1,
"name": "randomUserTypeName",
"users":
[
{
"id": 11,
"userTypeId": 1,
"userUrl": "https://userurl",
"username": "eee",
"password": "eee",
}
]
}
答案 0 :(得分:0)
如果您想通过userTypeName
之类的请求通过路由访问/api/User/userTypeName
,则您的操作应为
[HttpGet("{userTypeName}")]
public async Task<ActionResult<IEnumerable<User>>> GetAsync(string userTypeName) {
var result = await ctx.User
.Include(x => x.UserType)
.Where(x => x.UserType.Name.ToLower() == UserTypeName.ToLower())
.ToListAsync();
if (result == null) return BadRequest();
return result;
}
如果您想通过userTypeName
之类的请求从查询访问api/user?userTypeName=randomUserTypeName
,则您的操作应为
[HttpGet]
public async Task<ActionResult<IEnumerable<User>>> GetAsync([FromQuery(Name = "userTypeName")]string userTypeName) {
var result = await ctx.User
.Include(x => x.UserType)
.Where(x => x.UserType.Name.ToLower() == UserTypeName.ToLower())
.ToListAsync();
if (result == null) return BadRequest();
return result;
}