簡體   English   中英

ASP.Net 中基於屬性的路由/版本控制 WEB API 2.0

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

我正在嘗試在 Asp.Net Web API 中使用版本控制。 以下是項目的結構。 在此處輸入圖像描述

為了支持版本控制,我添加了Microsoft.AspNet.WebApi.Versioning NuGet package。 以下是 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 }
        );
    }

以下是 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            
    }
}

如果我在 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

請幫助我了解我在這里做錯了什么,這導致了上述錯誤。

您可以使用object ,其中包含名為Id的屬性作為操作UpdateEmployeeData參數,而不是直接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            
}

我希望你覺得這有幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM