ASP.Net WEB API 2.0 中基于属性的 Routing/Versioning

Attribute Based Routing/Versioning in ASP.Net WEB API 2.0

我正在尝试在 Asp.Net Web API 中使用版本控制。 以下是项目的结构。

为了支持版本控制,我添加了 Microsoft.AspNet.WebApi.Versioning NuGet 包。 以下是 WebApiConfig 的代码片段:

    public static void Register(HttpConfiguration config)
    {
        var constraintResolver = new DefaultInlineConstraintResolver()
        {
            ConstraintMap =
            {
                ["apiVersion"] = typeof(ApiVersionRouteConstraint)
            }
        };
        config.MapHttpAttributeRoutes(constraintResolver);
        config.AddApiVersioning();
        // Web API configuration and services

        // Web API routes
        //config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }

下面是来自控制器的代码:

[ApiVersion("1.0")]
[RoutePrefix("api/v{version:apiVersion}/employeemanagement")]
public class EmployeeManagementController : ApiController
{
    [Route("GetTest")]
    [HttpGet]
    public string GetTest()
    {
        return "Hello World";
    }

    [Route("GetTest2")]
    [HttpGet]
    public string GetTest2()
    {
        return "Another Hello World";
    }

    [Route("saveemployeedata")]
    [HttpPost]
    public async Task<GenericResponse<int>> SaveEmployeeData(EmployeeData employeeData, ApiVersion apiVersion)
    {
        //code goes here
    }

    [Route("updateemployeedata")]
    [HttpPost]
    public async Task<GenericResponse<int>> UpdateEmployeeData([FromBody]int id, ApiVersion apiVersion)
    {
        //code goes here            
    }
}

如果我在 UpdateEmployeeData 中使用 [FromBody],它会给出以下错误:

{
"Message": "The request is invalid.",
"MessageDetail": "The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Threading.Tasks.Task`1[AlphaTest.API.Models.ResponseModels.GenericResponse`1[System.Int32]] UpdateEmployeeData(Int32, Microsoft.Web.Http.ApiVersion)' in 'AlphaTest.API.Controllers.V1.EmployeeManagementController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter."
}

以下是 URL & 数据,我正在传递以生成上述错误: http://localhost:53963/api/v1.0/EmployeeManagement/updateemployeedata

如果我删除[FromBody],它会给我 404 未找到错误

请帮助我理解我在这里做错了什么,这导致了上述错误。

您可以使用包含名为 Id 的 属性 的 对象 作为操作 [=13] 的 参数 =] 不是直接 int Id,比如:

public class Request
{
    public int Id { get; set; }
}

操作将是:

[Route("updateemployeedata")]
[HttpPost]
public async Task<GenericResponse<int>> UpdateEmployeeData([FromBody]Request request, ApiVersion apiVersion)
{
    //code goes here            
}

希望对您有所帮助。