向WebApi添加CancellationToken导致415

时间:2019-06-17 20:02:26

标签: .net .net-core

我有一个.Net Core 2.1 WebAPI应用程序,其方法不带参数。当我向其中添加一个参数(CancellationToken cancellationToken)时,对其的所有请求都返回415 Unsupported media type。如果将用户定义的类作为参数,则得到的结果是相同的,因此我认为,CancellationToken的模型绑定可能无法正常工作,因为应该将其绑定到http取消令牌来源(尽管我知道2.1中存在问题)。

控制器:

[Authorize]
[ApiController]
[Route("api/[controller]")]
public class MyController : Controller
{
    [HttpGet]
    [Route("MyRoute")]
    public async Task<IList<MyObject>> MyRouteAsync(CancellationToken cancellationToken)

ConfigureServices:

        services.AddAuthentication(options =>
        {
            options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
        })
        .AddAzureAd(options => Configuration.Bind("AzureAd", options))
        .AddCookie();

        services.AddAuthorization(options =>
        {
            options.AddPolicy("DmpLicenseUpdaters", policy => policy.Requirements.Add(new DmpLicenseUpdatersRequirement()));
        });

        // Add framework services.
        services.AddMemoryCache();
        services.AddResponseCompression();
        services.AddMvc(options =>
        {
            options.Filters.Add(typeof(ApplicationVersionHeaderFilter));
            options.Filters.Add(typeof(ExecutionPerformanceCustomHeaderFilter));
        })
        .AddJsonOptions(options =>
        {
            options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
        });

配置:

        if (env.IsDevelopment())
        {
            //app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseHttpsRedirection();
        }

        app.UseStaticFiles();
        app.UseSpaStaticFiles();
        app.UseAuthentication();
        app.UseMvc();

1 个答案:

答案 0 :(得分:0)

您可以通过在配置 MVC 服务时将 AllowValidatingTopLevelNodes 显式设置为 true 来修复此 HTTP 415 状态代码错误:

services.AddMvcCore(options => options.AllowValidatingTopLevelNodes = true)

或者,您也可以 set the compatibility version 到 2.1 或更高版本,但这也会选择加入其他行为:

services.AddMvcCore().SetCompatibilityVersion(CompatibilityVersion.Version_2_1)

或者升级到 ASP.NET Core 3 或更高版本,我认为 CancellationToken 开箱即用,无需配置任何特殊内容。

相关问题