Подтвердить что ты не робот

Методы множественного получения MVC 6

Я пытаюсь поддерживать несколько методов Get() для каждого контроллера, а также только специально названные методы, доступные через web api. Я сделал это в MVC 5, но не могу понять, как это делается в MVC 6. Любые идеи? Спасибо.

4b9b3361

Ответ 1

Вы можете использовать ссылку маршрутизации атрибута -

[Route("api/[controller]")] /* this is the defualt prefix for all routes, see line 20 for overridding it */
public class ValuesController : Controller
{
    [HttpGet] // this api/Values
    public string Get()
    {
        return string.Format("Get: simple get");
    }

    [Route("GetByAdminId")] /* this route becomes api/[controller]/GetByAdminId */
    public string GetByAdminId([FromQuery] int adminId)
    {
        return $"GetByAdminId: You passed in {adminId}";
    }

    [Route("/someotherapi/[controller]/GetByMemberId")] /* note the / at the start, you need this to override the route at the controller level */
    public string GetByMemberId([FromQuery] int memberId)
    {
        return $"GetByMemberId: You passed in {memberId}";
    }

    [HttpGet]
    [Route("IsFirstNumberBigger")] /* this route becomes api/[controller]/IsFirstNumberBigger */
    public string IsFirstNumberBigger([FromQuery] int firstNum, int secondNum)
    {
        if (firstNum > secondNum)
        {
            return $"{firstNum} is bigger than {secondNum}";
        }
        return $"{firstNum} is NOT bigger than {secondNum}";
    }
}

Подробнее см. здесь http://nodogmablog.bryanhogan.net/2016/01/asp-net-5-web-api-controller-with-multiple-get-methods/

Ответ 2

У вас не может быть несколько методов Get с одинаковым шаблоном url. Вы можете использовать маршрутизацию атрибутов и настроить несколько методов GET для разных шаблонов URL.

[Route("api/[controller]")]
public class IssuesController : Controller
{
    // GET: api/Issues
    [HttpGet]
    public IEnumerable<string> Get()
    {
        return new string[] { "item 1", "item 2" };
    }

    // GET api/Issues/5
    [HttpGet("{id}")]
    public string Get(int id)
    {
        return "request for "+ id;
    }

    // GET api/Issues/special/5
    [HttpGet("special/{id}")]
    public string GetSpecial(int id)
    {
        return "special request for "+id;
    }
    // GET another/5
    [HttpGet("~/another/{id}")]
    public string AnotherOne(int id)
    {
        return "request for AnotherOne method with id:" + id;
    }
    // GET api/special2/5
    [HttpGet()]
    [Route("~/api/special2/{id}")]
    public string GetSpecial2(int id)
    {
        return "request for GetSpecial2 method with id:" + id;
    }
}

Вы можете видеть, что для определения шаблонов маршрута я использовал атрибуты HttpGet и Route.

С приведенной выше конфигурацией вы получите ответы ниже

URL-адрес запроса: yourSite/api/issues/

Результат ["value1","value2"]

URL-адрес запроса: yourSite/api/issues/4

Результат request for 4

URL-адрес запроса: yourSite/api/special2/6

Результат request for GetSpecial2 method with id:6

URL-адрес запроса: yourSite/other/3

Результат request for AnotherOne method with id:3