首页 > 解决方案 > API NET CORE:错误:400“'I' 是值的无效开始。路径:$ | LineNumber:0 | BytePositionInLine:0。”

问题描述

从带有 ajax 的页面调用服务时出现此错误:

{"type":"https://tools.ietf.org/html/rfc7231#section-6.5.1","title":"出现一个或多个验证错误。","status":400,"traceId" :"|5ee8d421-490444ac9bfc2da3.","errors":{"$":["'I' 是一个无效的值开始。路径: $ | LineNumber: 0 | BytePositionInLine: 0."]}}

这是我发送的 JSON:

{
    BndPublicado: false
    ChrCodAcceso: "C3C-007-000"
    ChrCookie: "sysses=fmHUrLdB3PLw1kpM5nW1c7AxI/yFUIkbM6Y4p8tN2ftUsWLiPfSBImg6AGnxnuiJYU/BOiToidI/gC5Lh+XzCvtOlGP6jwOPcdfM6tn5nAEQriqQR5Xqpa17/sFweUuOe1JckjC1JevQ9kBhlBICKA=="
    IntCGE: 1
    IntEmpresa: 1
    IntUsuario: 1
}

这是来自 AJAX 的调用

function fn_ValidateAccess (p_Access){

    var v_PathExternal = 'http://localhost:40452/EXAMPLE..';

    var v_PostJSON = fn_CreateSessionData(p_Access);

    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: v_PathExternal,
        dataType: "json",
        data: v_PostJSON,
        success: function (data){ 
          return data;
        },
        failure: function (data) {
            alert(data.responseText);
            return null;
        },
        error: function (data){ 
            alert("No se ha podido completar la validación de acceso." + data.responseText); 
            return null;
        }
    });
}

这是我的服务的启动:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(options =>
        {
            options.AddPolicy("Policy",
                builder =>
                {
                    builder.WithOrigins("*").AllowAnyHeader().AllowAnyMethod();
                });
        });

        services.AddControllers().AddFluentValidation(cfg => cfg.RegisterValidatorsFromAssemblyContaining<GetValuesDropDownList>());

        services.AddMediatR(typeof(GetValuesDropDownList.Handler).Assembly);

    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseRouting();

        app.UseCors();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }

这是我的控制器

        [ResponseType(typeof(Task<ActionResult<ResultsValidateAccess>>))]
        [HttpPost("[action]")]
        public async Task<ActionResult<ResultsValidateAccess>> postValidarSession([FromBody] ValidateAccess.Execute request)
        {
            return await _mediator.Send(request);
        }

标签: asp.net-core-webapiasp.net-core-3.1

解决方案


就我而言,我发现这是在 ModelBinder 尝试反序列化从 Ajax 发布的 DATA 时发生的。发布的数据被编码为非 Json 格式,然后 System.Text.Json.Serialization 生成错误。

要进行调查,请查看 Ajax 发布到控制器的数据格式。或者,在发送请求之前尝试使用 JSON.stringify() 序列化 v_PostJson


推荐阅读