【发布时间】:2020-10-03 14:10:41
【问题描述】:
我正在尝试在 Asp.Net Web API 中使用版本控制。 以下是项目的结构。
为了支持版本控制,我添加了 Microsoft.AspNet.WebApi.Versioning NuGet 包。 下面是WebApiConfig的sn-p代码:
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 Not found error。
请帮助我了解我在这里做错了什么,这导致了上述错误。
【问题讨论】:
标签: c# asp.net-web-api asp.net-web-api2 asp.net-web-api-routing