添加Microsoft.AspNetCore.OData.Versioning后,为什么我的HTTP Post不再传递正文内容

问题描述 投票:0回答:2

我正在开发一个ASP.NET Core 2.2 API,它通过Microsoft.AspNetCore.Odata v7.1.0 NuGet实现OData。我让一切正常,所以我决定通过Microsoft.AspNetCore.OData.Versioning v3.1.0添加API Versioning。

现在,我的控制器中的GET和GET {id}方法可以正确地进行版本控制。例如,我可以使用URL访问GET列表端点方法

~/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);
    }

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

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

在尝试实现API Versioning之前,我使用的是模型构建器类,如下所示;

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 - > Configure方法,如下面的代码片段所示;

        // 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 Versioning 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();
            });

我觉得问题是模型在某种程度上不能正确匹配,但我不明白为什么它不是

更新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; }
}

这是Postman的请求机构;

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

有任何想法吗?

c# asp.net-core odata api-versioning microsoft-odata
2个回答
1
投票

事实证明,问题是因为我没有使用驼峰案例作为Postman请求体中的属性名称。这不是单独的Microsoft.AspNetCore.Odata的问题,但是一旦我添加了Microsoft.AspNetCore.Odata.Versioning NuGet包,它就失败了属性名称的大写起始字符。似乎Microsoft.AspNetCore.Odata.Versioning使用它自己的MediaTypeFormatter来实现更低的驼峰情况。我在下面的GitHub帖子中发现了这个; https://github.com/Microsoft/aspnet-api-versioning/issues/310


0
投票

没有自定义的MediaTypeFormatter,但3.0中的行为确实发生了变化,因为使用camel大小写似乎是大多数基于JSON的API的默认设置。但这很容易回复。

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

这也是您执行或更改与模型构建器相关的任何其他设置的地方。调用工厂方法以根据API版本创建新的模型构建器。

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

我希望有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.