Web API HttpGetAttribute错误

时间:2018-08-08 14:05:31

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

我正在制作一个用于访问SQL Server数据库的API。我已经编写了所需的模型和类,因此现在需要创建一个控制器来连接所有内容。

目前我的控制器代码是

using Microsoft.AspNetCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using EPOSDatabase_API.DataProvider;
using EPOSDatabase_API.Models;
using System.Web.Http;

namespace EPOSDatabase_API.Controllers
{

[Route("api/[controller]")]
public class CategoryController : ApiController
{
    private ICategoryDataProvider categoryDataProvider;

    public CategoryController(ICategoryDataProvider categoryDataProvider)
    {
        this.categoryDataProvider = categoryDataProvider;
    }

    [HttpGet]
    public async Task<IEnumerable<Category>> Get()
    {
        return await this.categoryDataProvider.GetCategories();
    }

    [HttpGet("{id}")]
    public async Task<Category> Get(int Category_ID)
    {
        return await this.categoryDataProvider.GetCategory(Category_ID);
    }

    [HttpPost]
    public async Task Post([FromBody]Category category)
    {
        await this.categoryDataProvider.AddCategory(category);
    }

    [HttpPut("{id}")]
    public async Task Put(int Category_ID, [FromBody]Category category)
    {
        await this.categoryDataProvider.UpdateCategory(category);
    }

    [HttpDelete("{id}")]
    public async Task Delete(int Category_ID)
    {
        await this.categoryDataProvider.DeleteCategory(Category_ID);
    }
  }
}

但是对于线路

[HttpGet("{id}")][HttpPut("{id}")][HttpDelete("{id}")]出现错误

  

'HttpGet / Put / DeleteAttribute'不包含带有1个参数的构造函数

为什么会发生此错误,也许我缺少一个using参考吗?

1 个答案:

答案 0 :(得分:0)

[HttpGet]
public async Task<Category> Get(int id)
{
    return await this.categoryDataProvider.GetCategory(Category_ID);
}

[Route("{id}")]
public async Task<Category> Get(int id)
{
   return await this.categoryDataProvider.GetCategory(Category_ID);
}

都应该做到这一点。 ASP.NET Web API知道如何将方法签名与传入请求进行匹配。 或者,如果您想更改默认行为,则必须在方法签名中将变量名称保留为参数名称。

您可以阅读有关ASP.NET Web API 2 in here

中的属性路由的更多信息。