【问题标题】:How to tell apart by Web Api which method to use to return data [duplicate]如何通过Web Api区分使用哪种方法返回数据[重复]
【发布时间】:2017-04-23 03:24:59
【问题描述】:

我是 asp.net Web Api 的新手。我用ValuesController创建了一个简单的Web Api App

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

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)
        {
        }
    }
}

【问题讨论】:

    标签: c# asp.net-web-api asp.net-web-api-routing


    【解决方案1】:

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

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

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

    原题提供的示例代码的cmets中其实已经注明了。

    参考Routing in ASP.NET Web API

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-05
      • 1970-01-01
      • 2017-06-05
      • 2017-01-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多