如何通过 Web 区分 Api 对 return 数据使用哪种方法

How to tell apart by Web Api which method to use to return data

我是 asp.net Web Api 的新手。我用 ValuesController

创建了一个简单的 Web Api 应用程序

当我发出请求时我会得到什么:

api/values/5

当有:

public string Get(int id) { }
public void Delete(int id) { }

控制器中的方法。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace my2ndWebApi.Controllers
{
    public class ValuesController : ApiController
    {
        // GET api/values
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/values/5
        public string Get(int id)
        {
            return "value";
        }

        // POST api/values
        public void Post([FromBody]string value)
        {
        }

        // PUT api/values/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/values/5
        public void Delete(int id)
        {
        }
    }
}

这取决于发出请求时使用的 HTTP 动词。

api/values/5GET 请求将匹配 public string Get(int id)

api/values/5DELETE 请求将匹配 public void Delete(int id)

其实在原题提供的示例代码的注释中已经说明了

引用Routing in ASP.NET Web API