我正在尝试在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
的属性的object作为操作UpdateEmployeeData
的parameter而不是直接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
}
希望您能找到帮助。