在 ASP.NET REST-API 中检索具有两个不同属性的对象
Retrieve object with two different attributes in ASP.NET REST-API
我在 ASP.NET 中有一个 REST API 给 CRUD 人。这个人 class 看起来像这样:
class Person
{
private int id;
private string name;
private int age;
private string email;
}
我已经可以通过 id
使用以下路线找回一个人:
[HttpGet]
[Route("person/{personId}")]
public IActionResult Person(int personId)
{
// This code doesn't matter
var person = _personManager.Get(personId);
if (person is null) return NotFound("Person not found");
return Ok(person.ToDto());
}
但问题是我还想通过电子邮件检索一个人。我该怎么做?这是一个选项吗?
// Could this work?
[HttpGet]
[Route("person/email/{personEmail}")]
public IActionResult Person(string email)
{
// This code doesn't matter
var person = _personManager.GetByMail(personEmail);
if (person is null) return NotFound("Person not found");
return Ok(person.ToDto());
}
或者有更好的方法吗?当前路线[Route("person/{personId}")]
无法更改,因为它已经被多次使用。
谢谢。
试试这个:
[Route("person/{id}")]
[Route("personById/{id}")]
public IActionResult GetPersonById(int id)
{
// This code doesn't matter
var person = _personManager.Get(id);
if (person is null) return NotFound("Person not found");
return Ok(person.ToDto());
}
[Route("personByEmail/{email}")]
public IActionResult GetPersonByEmail(string email)
{
// This code doesn't matter
var person = _personManager.GetByMail(personEmail);
if (person is null) return NotFound("Person not found");
return Ok(person.ToDto());
}
我在 ASP.NET 中有一个 REST API 给 CRUD 人。这个人 class 看起来像这样:
class Person
{
private int id;
private string name;
private int age;
private string email;
}
我已经可以通过 id
使用以下路线找回一个人:
[HttpGet]
[Route("person/{personId}")]
public IActionResult Person(int personId)
{
// This code doesn't matter
var person = _personManager.Get(personId);
if (person is null) return NotFound("Person not found");
return Ok(person.ToDto());
}
但问题是我还想通过电子邮件检索一个人。我该怎么做?这是一个选项吗?
// Could this work?
[HttpGet]
[Route("person/email/{personEmail}")]
public IActionResult Person(string email)
{
// This code doesn't matter
var person = _personManager.GetByMail(personEmail);
if (person is null) return NotFound("Person not found");
return Ok(person.ToDto());
}
或者有更好的方法吗?当前路线[Route("person/{personId}")]
无法更改,因为它已经被多次使用。
谢谢。
试试这个:
[Route("person/{id}")]
[Route("personById/{id}")]
public IActionResult GetPersonById(int id)
{
// This code doesn't matter
var person = _personManager.Get(id);
if (person is null) return NotFound("Person not found");
return Ok(person.ToDto());
}
[Route("personByEmail/{email}")]
public IActionResult GetPersonByEmail(string email)
{
// This code doesn't matter
var person = _personManager.GetByMail(personEmail);
if (person is null) return NotFound("Person not found");
return Ok(person.ToDto());
}