简体   繁体   中英

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

I'm trying to use versioning in Asp.Net Web API. Following is the structure of the project. 在此处输入图像描述

To support versioning I've added Microsoft.AspNet.WebApi.Versioning NuGet package. Following is the code snippet of 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 }
        );
    }

And below is the code from controller:

[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            
    }
}

If I use [FromBody] in UpdateEmployeeData, it gives following error:

{
"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."
}

Following is the URL & data, I'm passing to generate above error: http://localhost:53963/api/v1.0/EmployeeManagement/updateemployeedata 在此处输入图像描述

If I remove[FromBody] it gives me 404 Not found error .

Please help me understand what I'm doing wrong here, which is causing above mentioned error.

You could use object that contains property called Id as parameter of the action UpdateEmployeeData not directly the int Id , like:

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

The action will be:

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

I hope you find this helpful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM