简体   繁体   English

使用来自 NewtonSoft 的 Json Schema Validator 示例代码并获得 400 Bad Request

[英]Using Json Schema Validator sample code from NewtonSoft and getting a 400 Bad Request

So I'm trying to wrap my head around writing an API for work and one portion of it is validating incoming JSON against a schema.因此,我正试图全神贯注地编写 API 来工作,其中一部分是针对模式验证传入的 JSON。 I have created a simple schema as POC in order to get this API up and running.为了让这个 API 启动并运行,我创建了一个简单的模式作为 POC。 I am using NewtonSoft.Json.Schema as this seems to be the best way to achieve what I'm after, and I can't stress this enough, there is free sample code!我正在使用 NewtonSoft.Json.Schema 因为这似乎是实现我所追求的最佳方式,我不能强调这一点,有免费的示例代码!

This is my sample schema, with sample json, showing that it validates.这是我的示例架构,带有示例 json,表明它已验证。

https://www.jsonschemavalidator.net/s/jldyV4ng https://www.jsonschemavalidator.net/s/jldyV4ng

In the sample code, a class ValidRequest is used and this contains the text of the schema and json, so I've attempted to leverage that code as-is.在示例代码中,使用了 class ValidRequest,其中包含模式文本和 json,因此我尝试按原样利用该代码。

Invoke-RestMethod -Method Post -Uri https://localhost:44392/api/jsonschema/validate -Body ('{"Schema":"https://gist.githubusercontent.com/jeffpatton1971/c2d3ee98a37766a2784ccd626b9b8ca2/raw/edee46a24c1439e09490e415fa27943a08b353dd/schema.json","Json":"{}"}') -ContentType application/json

valid errors
----- ------
False {@{message=Required properties are missing from object: checked, dimensions, id, name, price, tags.; lineNumber=1; linePosition=1; path=; value=System.Object[]; schema=; schemaId=http://example.com/root.json; schemaBaseUri=; er...

This appears to work as advertised, the validator is telling me that my empty json string is missing stuff.这似乎像宣传的那样工作,验证器告诉我我的空 json 字符串丢失了东西。 What I'm struggling with is when I attempt to pass in the correct json that works on the link above.我正在苦苦挣扎的是,当我尝试传递在上面的链接上有效的正确 json 时。

Invoke-RestMethod -Method Post -Uri https://localhost:44392/api/jsonschema/validate -Body ('{"Schema":"https://gist.githubusercontent.com/jeffpatton1971/c2d3ee98a37766a2784ccd626b9b8ca2/raw/edee46a24c1439e09490e415fa27943a08b353dd/schema.json","Json":{"checked":true,"dimensions":{"width":7,"height":8},"id":1,"name":"thing","price":1,"tags":[]}}') -ContentType application/json
Invoke-RestMethod : The remote server returned an error: (400) Bad Request.
At line:1 char:1
+ Invoke-RestMethod -Method Post -Uri https://localhost:44392/api/jsons ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

I feel that perhaps I've got the json string wrong in some fashion but I'm not clear.我觉得也许我的 json 字符串在某种程度上是错误的,但我不清楚。 Below is the code from my POC.以下是我的 POC 中的代码。 In my example I use the request.schema as a url and then I grab it from the URL passed in via WebClient.在我的示例中,我使用 request.schema 作为 url,然后从通过 WebClient 传入的 URL 中获取它。 It parses the schema as you would expect, and for the null json string, it parsed that json as you would expect.它会按照您的预期解析模式,对于 null json 字符串,它会按照您的预期解析 json。 When I pass in an actual json payload I get the error above.当我传入一个实际的 json 有效负载时,我得到了上面的错误。 I have placed a breakpoint at the top of the ValidateResponse code, but I never get that far, so that error is thrown before I get to any code that I can trace.我在 ValidateResponse 代码的顶部放置了一个断点,但我从来没有走到那一步,所以在我到达任何我可以跟踪的代码之前就会引发错误。

Any help would be appreciated, I feel I'm doing something silly, the project is the asp.net core web api project, and I've followed the defaults and added an read/write api controller named JsonSchemaController. Any help would be appreciated, I feel I'm doing something silly, the project is the asp.net core web api project, and I've followed the defaults and added an read/write api controller named JsonSchemaController. My startup.cs is below the JsonSchemaController.cs.我的 startup.cs 在 JsonSchemaController.cs 之下。

JsonSchemaController.cs JsonSchemaController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Schema;
using System.Net;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace SchemaValidator.Properties
{
    [Route("api/[controller]")]
    [ApiController]
    public class JsonSchemaController : ControllerBase
    {
        public class ValidateRequest
        {
            public string Json { get; set; }
            public string Schema { get; set; }
        }

        public class ValidateResponse
        {
            public bool Valid { get; set; }
            public IList<ValidationError> Errors { get; set; }
        }

        // GET: api/<JsonSchemaController>
        [HttpGet]
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/<JsonSchemaController>/5
        [HttpGet("{id}")]
        public string Get(int id)
        {
            return "value";
        }

        [HttpPost]
        [Route("validate")]
        public ValidateResponse Valiate(ValidateRequest request)
        {
            WebClient wget = new System.Net.WebClient();
            var jsonSchema = wget.DownloadString(request.Schema);

            // load schema
            JSchema schema = JSchema.Parse(jsonSchema);
            JToken json = JToken.Parse(request.Json);

            // validate json
            IList<ValidationError> errors;
            bool valid = json.IsValid(schema, out errors);

            // return error messages and line info to the browser
            return new ValidateResponse
            {
                Valid = valid,
                Errors = errors
            };
        }

    }
}

Startup.cs启动.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace SchemaValidator
{
    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
        }

        // 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.UseEndpoints(endpoints =>
            {
                endpoints.MapGet("/", async context =>
                {
                    await context.Response.WriteAsync("Hello World!");
                });
                endpoints.MapControllerRoute(
                    "default", "{controller=Home}/{action=Index}/{id?}"
                    );
            });
        }
    }
}

Package Manager Output Package 经理 Output

PM> Install-Package newtonsoft.json
Restoring packages for C:\Users\JeffreyPatton\source\repos\SchemaValidator\SchemaValidator\SchemaValidator.csproj...
Installing NuGet package newtonsoft.json 13.0.1.
Committing restore...
Writing assets file to disk. Path: C:\Users\JeffreyPatton\source\repos\SchemaValidator\SchemaValidator\obj\project.assets.json
Restored C:\Users\JeffreyPatton\source\repos\SchemaValidator\SchemaValidator\SchemaValidator.csproj (in 22 ms).
Successfully installed 'Newtonsoft.Json 13.0.1' to SchemaValidator
Executing nuget actions took 1.1 sec
Time Elapsed: 00:00:01.6936888
PM> Install-Package newtonsoft.json.schema
Restoring packages for C:\Users\JeffreyPatton\source\repos\SchemaValidator\SchemaValidator\SchemaValidator.csproj...
Installing NuGet package newtonsoft.json.schema 3.0.14.
Committing restore...
Writing assets file to disk. Path: C:\Users\JeffreyPatton\source\repos\SchemaValidator\SchemaValidator\obj\project.assets.json
Restored C:\Users\JeffreyPatton\source\repos\SchemaValidator\SchemaValidator\SchemaValidator.csproj (in 9 ms).
Successfully installed 'Newtonsoft.Json.Schema 3.0.14' to SchemaValidator
Executing nuget actions took 1.01 sec
Time Elapsed: 00:00:01.4802313

The problem I'm seeing has to do with how the JSON is being constructed outside of the API.我看到的问题与 JSON 如何在 API 之外构建有关。 @dbc's post above with fiddler put me on the right track. @dbc 上面与提琴手的帖子让我走上了正确的轨道。 Then working with postman helped me out even more.然后与 postman 合作帮助了我更多。

{
    "Schema":"https://gist.githubusercontent.com/jeffpatton1971/c2d3ee98a37766a2784ccd626b9b8ca2/raw/edee46a24c1439e09490e415fa27943a08b353dd/schema.json",
    "Json": "{\"checked\":true,\"dimensions\":{\"width\":7,\"height\":8},\"id\":1,\"name\":\"thing\",\"price\":1,\"tags\":[]}"
}

This escaped json works as expected, I appreciate all the feedback.这个逃脱的 json 按预期工作,我感谢所有反馈。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 即使使用Newtonsoft.Json.JsonConvert进行序列化,REST服务也会收到(400)错误的特殊字符请求 - Rest service getting (400) Bad Request for special characters even after serializing with Newtonsoft.Json.JsonConvert 收到错误代码400剩余WCF客户端错误请求 - Getting Error Code 400 Bad Request for Rest WCF Client Solr收到错误请求(400) - Getting bad request (400) on solr 使用 RestSharp 获取 ExactOnline 的访问令牌时出现 400 Bad Request - 400 Bad Request when getting access token for ExactOnline using RestSharp 我正在尝试使用 c# 从 Twitter api 获取请求令牌,但收到 400 个错误的请求错误 - I am trying to get request token from Twitter api using c#, but getting 400 bad request error 来自 Angular 9 中 WebApi 的 400 错误请求(使用 HttpClient) - 400 Bad Request From WebApi In Angular 9 (using HttpClient) Elasticsearch DeleteByQuery无法正常工作,收到400错误请求 - Elasticsearch DeleteByQuery not working, getting 400 bad request 使用我的 firebase URL 获得 400(错误请求) - Getting 400 (Bad Request) with my firebase URL REST 服务收到 400 个错误请求 - REST Service Getting 400 bad request 发布Json对象时出现400(错误请求) - 400(Bad Request) when a Json object is posted
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM