如何在 .net core web api 中使用 HTTP get 方法传递参数?

moj*_*ojo 0 .net c# .net-core asp.net-core asp.net-core-webapi

我正在尝试使用 .net core web api 构建一个简单的 web api,它将执行基本的数学运算。我编写了由多个 get 方法组成的控制器部分,当它被调用时,它返回执行操作的值。控制器代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace Calculation.Controllers
{
    [Route("api/[controller]")]
    public class MathController : Controller
    {
        [HttpGet("Add")]
        public int Add(int value1, int value2)
        {
            return value1 + value2;
        }
        [HttpGet("Subtract")]
        public int Substract(int value1, int value2)
        {
            return value1 - value2;
        }
        [HttpGet("Multiply")]
        public int Multiply(int value1, int value2)
        {
            return value1 * value2;
        }
        [HttpGet("Division")]
        public int Division(int value1, int value2)
        {
            return value1 / value2;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

那么如何使用 api 传递参数值,以便它返回数学运算的值。就像如果我去https://localhost:44309/api/math/add/ {{argument values value1 and value 2 say 25 and 25}} 它会返回 50 同样https://localhost:44309/api/math/减去/ {{参数值 value1 和 value 2 说 25 和 25}} 它将返回 0

小智 5

您可以使用相同的 url 传递参数 https://localhost:44309/api/math/add?value1=25&value2=25 或将路由更改为

[HttpGet("Add/{value1}/{value2}")]
Run Code Online (Sandbox Code Playgroud)

进而 https://localhost:44309/api/math/add/25/25