WebApi实现

时间:2018-01-12 09:52:35

标签: asp.net-web-api

我正在学习WebAP,之前我曾在Webservices工作过。

我对MVCWebApi的实现很困惑。

我的理解 - 它基于HTTP协议,因此它支持PUT,GET,POST,DELETE方法。

在一些教程中,我看到在控制器中添加了[HttpPost]属性,在某些情况下,这个属性没有被添加,但仍然可以正常工作。 这可能是一个小问题,但会清除我的概念。请帮助。

示例 - 即使没有HttpGet或HttpPost属性,也会通过http://localhost:60486/api/products以json格式提供有关员工的所有详细信息。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using WebApiTest.Models;

namespace WebApiTest.Controllers
{
    public class ProductsController : ApiController
    {
        Product[] products = new Product[]
           {
            new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 },
            new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M },
            new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M }
           };

        public IEnumerable<Product> GetAllProducts()
        {
            return products;
        }

        public Product GetProduct(int id)
        {
            var product = products.FirstOrDefault((p) => p.Id == id);

            return product;
        }
    }
}

1 个答案:

答案 0 :(得分:1)

<强> EDIT2

attribute-routing-in-web-api-2

  

HTTP方法Web API还根据HTTP方法选择操作   请求(GET,POST等)。默认情况下,Web API会查找   不区分大小写,与控制器方法名称的开头匹配。   例如,名为PutCustomers的控制器方法与HTTP匹配   PUT请求。

     

您可以通过使用任何方法修饰mathod来覆盖此约定   以下属性:2

     

[HttpDelete] [HttpGet] [HttpHead] [HttpOptions] [HttpPatch] [HttpPost]   [HttpPut]

默认情况下,如果操作方法名称以HttpAttributte开头 例如:

public IHttpActionResult GetValue(int id)
{
    return Ok();
}

api知道这个动作是Get,所以你不必添加[HttpGet]

但是如果你想拥有不同的动作名称,那么你必须添加[HttpAttribute]

例如

[HttpGet]
public IHttpActionResult Value(int id)
{
    return Ok();
}

修改

基于你的例子:

//This will work, because name GetAllProducts starts with Get, so api knows 
///its HttpGet, You don't have to use [HttpGet]Attribute  (but You can add 
//it, and it will work as well
public IEnumerable<Product> GetAllProducts()
{
    return products;
}

//This will work, because name GetProduct starts with Get, so api knows 
///its HttpGet, You don't have to use [HttpGet]Attribute  (but You can add 
//it, and it will work as well
public Product GetProduct(int id)
{
    var product = products.FirstOrDefault((p) => p.Id == id);

    return product;
}

但是如果您将名称更改为:

//This will NOT work, because name AllProducts dont starts with Get, so api dont know what http method to use
///You have to add [HttpGet]
public IEnumerable<Product> AllProducts()
{
    return products;
}

所以正确的实现(在名称更改后)是这样的:

[HttpGet]
public IEnumerable<Product> AllProducts()
{
    return products;
}

最后一件事,你用属性更改默认的http maping:

//This action will response to POST, not get
[HttpPost]
public IEnumerable<Product> GetAllProducts()
{
    return products;
}