C# WebApi增加多个控制器的方法

Posted 何以解忧 `唯有暴富

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C# WebApi增加多个控制器的方法相关的知识,希望对你有一定的参考价值。

增加多个控制器的方法

//路由设置controller中要和ValuesController中的Values同名才可以访问的到,例http://127.0.0.1:6565/api/values/area?r=2

[Route("api/[controller]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {
        private readonly IHttpContextAccessor httpContextAccessor;
        public ValuesController(IHttpContextAccessor httpContextAccessor)
        {
            this.httpContextAccessor = httpContextAccessor;
        }
        [HttpGet("area")]
        public ActionResult<double> Get(string r)
        {
            return Math.PI * Math.Pow(double.Parse(r), 2);
        }
     }

//http://127.0.0.1:6565/api/general/area?r=2

//路由设置
    [Route("api/[controller]")]
    [ApiController]
    public class GeneralController : ControllerBase
    {
        private readonly IHttpContextAccessor httpContextAccessor;
        public GeneralController(IHttpContextAccessor httpContextAccessor)
        {
            this.httpContextAccessor = httpContextAccessor;
        }

        [HttpGet("area")]
        public ActionResult<double> Get(string r)
        {
            return Math.PI* Math.Pow(double.Parse(r),2);
        }
    }

launchSettings.json

{
  "$schema": "http://json.schemastore.org/launchsettings.json",
  "profiles": {
    "WebApi": {
      "commandName": "Project",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      },
      "applicationUrl": "http://localhost:6565"
    }
  }
}

通过json传递参数

 

  [HttpGet("velocity")]
        public ActionResult<double> GetVelocity(FlowVelocity flowVelocity)
        {
            double v = (flowVelocity.Q / (Math.PI * Math.Pow(flowVelocity.R, 2))) / 3600;
            return v;
        }
public class FlowVelocity { public double R { get; set; } public double Q { get; set; } }

以上是关于C# WebApi增加多个控制器的方法的主要内容,如果未能解决你的问题,请参考以下文章

C# WebApi之接口返回类型详解

WebApi一个控制器中定义多个Get方法。

C#通过WebAPI控制器将Excel xls发送到js并将其保存为文件

Web API 控制器中多个 HttpPost 方法的共享逻辑

CORS 多个标头

c# webapi post多个参数