为什么在添加Microsoft.AspNetCore.OData.Versioning

时间:2019-03-15 17:50:48

标签: c# asp.net-core odata api-versioning microsoft-odata

我正在研究一个ASP.NET Core 2.2 API,该API正在通过Microsoft.AspNetCore.Odata v7.1.0 NuGet实现OData。我一切正常,所以我决定通过Microsoft.AspNetCore.OData.Versioning v3.1.0添加API版本控制。

现在,我的控制器中的GET和GET {id}方法可以正确使用版本控制。例如,我可以使用URL进入GET list端点方法

~/api/v1/addresscompliancecodes

~/api/addresscompliancecodes?api-version=1.0

但是,当我尝试创建新记录时,请求将路由到控制器中的正确方法,但是现在请求正文内容并未传递给POST控制器方法

我一直在遵循Microsoft.ApsNetCore.OData.Versioning GitHub

中的示例

我的控制器中有HttpPost方法;

    [HttpPost]
    [ODataRoute()]
    public async Task<IActionResult> CreateRecord([FromBody] AddressComplianceCode record, ODataQueryOptions<AddressComplianceCode> options)
    {

        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        _context.Add(record);
        await _context.SaveChangesAsync();

        return Created(record);
    }

当我调试时,请求正确地路由到控制器方法,但是“ record”变量现在为空,而在为API Versioning添加代码更改之前,它已正确填充。

我怀疑这是我使用模型构建器的方式,因为该代码已更改为支持API版本控制。

在尝试实现API版本控制之前,我使用了如下所示的模型构建器类;

public class AddressComplianceCodeModelBuilder
{

    public IEdmModel GetEdmModel(IServiceProvider serviceProvider)
    {
        var builder = new ODataConventionModelBuilder(serviceProvider);

        builder.EntitySet<AddressComplianceCode>(nameof(AddressComplianceCode))
            .EntityType
            .Filter()
            .Count()
            .Expand()
            .OrderBy()
            .Page() // Allow for the $top and $skip Commands
            .Select(); 

        return builder.GetEdmModel();
    }

}

还有一个Startup.cs->配置方法,如下面的代码片段所示;

        // Support for OData $batch
        app.UseODataBatching();

        app.UseMvc(routeBuilder =>
        {
            // Add support for OData to MVC pipeline
            routeBuilder
                .MapODataServiceRoute("ODataRoutes", "api/v1",
                    modelBuilder.GetEdmModel(app.ApplicationServices),
                    new DefaultODataBatchHandler());



        });

它与控制器的HttpPost方法中的[FromBody]一起使用。

但是,在遵循API版本控制OData GitHub中的示例时,我现在使用的是如下所示的Configuration类,而不是之前的模型构建器;

public class AddressComplianceCodeModelConfiguration : IModelConfiguration
{

    private static readonly ApiVersion V1 = new ApiVersion(1, 0);

    private EntityTypeConfiguration<AddressComplianceCode> ConfigureCurrent(ODataModelBuilder builder)
    {
        var addressComplianceCode = builder.EntitySet<AddressComplianceCode>("AddressComplianceCodes").EntityType;

        addressComplianceCode
            .HasKey(p => p.Code)
            .Filter()
            .Count()
            .Expand()
            .OrderBy()
            .Page() // Allow for the $top and $skip Commands
            .Select();


        return addressComplianceCode;
    }
    public void Apply(ODataModelBuilder builder, ApiVersion apiVersion)
    {
        if (apiVersion == V1)
        {
            ConfigureCurrent(builder);
        }
    }
}

然后将我的Startup.cs-> Configure方法更改为如下所示;

    public void Configure(IApplicationBuilder app,
        IHostingEnvironment env, 
        VersionedODataModelBuilder modelBuilder)
    {

        // Support for OData $batch
        app.UseODataBatching();

        app.UseMvc(routeBuilder =>
        {
            // Add support for OData to MVC pipeline
            var models = modelBuilder.GetEdmModels();
            routeBuilder.MapVersionedODataRoutes("odata", "api", models);
            routeBuilder.MapVersionedODataRoutes("odata-bypath", "api/v{version:apiVersion}", models);
        });


    }

如果相关,我的Startup.cs-> ConfigureServices中将包含以下代码;

        // Add Microsoft's API versioning
        services.AddApiVersioning(options =>
        {
            // reporting api versions will return the headers "api-supported-versions" and "api-deprecated-versions"
            options.ReportApiVersions = true;
        });

        // Add OData 4.0 Integration
        services.AddOData().EnableApiVersioning();

        services.AddMvc(options =>
            {
                options.EnableEndpointRouting = false; // TODO: Remove when OData does not causes exceptions anymore
            })
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
            .AddJsonOptions(opt =>
            {
                opt.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            });

我认为问题出在某种程度上,模型无法正确匹配,但我无法确切知道为什么不匹配

UPDATE 3/18/19-其他信息

这是我的实体类;

[Table("AddressComplianceCodes")]
public class AddressComplianceCode : EntityBase
{
    [Key]
    [Column(TypeName = "char(2)")]
    [MaxLength(2)]
    public string Code { get; set; }

    [Required]
    [Column(TypeName = "varchar(150)")]
    [MaxLength(150)]
    public string Description { get; set; }
}

和EntityBase类;

public class EntityBase : IEntityDate
{
    public bool MarkedForRetirement { get; set; }

    public DateTimeOffset? RetirementDate { get; set; }

    public DateTimeOffset? LastModifiedDate { get; set; }

    public string LastModifiedBy { get; set; }

    public DateTimeOffset? CreatedDate { get; set; }

    public string CreatedBy { get; set; }

    public bool Delete { get; set; }

    public bool Active { get; set; }
}

这是邮递员的请求正文;

{   
    "@odata.context": "https://localhost:44331/api/v1/$metadata#AddressComplianceCodes",
    "Code": "Z1",
    "Description": "Test Label - This is a test for Z1",
    "Active": true
}

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

事实证明,问题出在我的邮递员请求正文中,因为我没有使用驼峰大小写作为属性名称。单独使用Microsoft.AspNetCore.Odata并不是一个问题,但是一旦添加了Microsoft.AspNetCore.Odata.Versioning NuGet程序包,它就会失败,并使用属性名称的大写开头字符。似乎Microsoft.AspNetCore.Odata.Versioning使用它自己的MediaTypeFormatter来启用小写驼峰格式。我在以下GitHub帖子中发现了这一点; https://github.com/Microsoft/aspnet-api-versioning/issues/310

答案 1 :(得分:0)

没有自定义MediaTypeFormatter,但是行为在3.0中确实发生了变化,因为使用骆驼套似乎是大多数基于JSON的API的默认设置。但是,这很容易还原。

modelBuilder.ModelBuilderFactory = () => new ODataConventionModelBuilder();
// as opposed to the new default:
// modelBuilder.ModelBuilderFactory = () => new ODataConventionModelBuilder().EnableLowerCamelCase();

这也是您执行或更改与模型构建器相关的任何其他设置的地方。调用factory方法可为每个API版本创建一个新的模型构建器。

值得指出的是,您不需要需要两次映射路线。为了演示目的,配置了 by查询字符串 by URL路径。您应该选择其中一个,然后删除不使用的一个。

我希望有帮助。