简体   繁体   中英

Long string in JSON array causes 400 Bad Request in .NET Core Web API

I'm sending an array containing a very long string from a JavaScript app (using the fetch API) to a .NET Core Web API, like this:

"FirstName LastName (Country)
 TEXT
    INFORMATION:  ^MOM?ROVAL LETTER REQUIRED.
    INFORMATION: MORE TEXT HERE
    .... around 20 more lines
"

The text could contain a range of characters, including line breaks, etc. (I think some of the characters are encoded CR and LF characters). It causes a 400 Bad Request when I send it to a .NET Core Web API. If I change the text to something like "test" then it works.

Is there an easy way I can format the text so that the Web API will accept it?

If you're getting a 400 Bad Request with ≈25 lines of relatively short strings then the most likely explanation is that your JavaScript is submitting these data via a GET request, thus hitting the limits for the query string length.

While the HTTP standard doesn't actually specify a limit to the length of a request , most servers have default limits for different methods.

For Internet Information Server (IIS), for example, this is:

  • URL: 4,096 bytes (4KB)
  • Query String ( GET ): 2,048 bytes (2KB)
  • Content ( POST ): 30,000,000 bytes (≈28.6MB)

If you happen to be hosting your ASP.NET Core application on IIS, and you have the Request Filtering feature installed ( instructions ), these limits can be modified in the web.config file ( reference ):

<configuration>
   <system.webServer>
      <security>
         <requestFiltering>
            <requestLimits maxUrl="2048" maxQueryString="1024" />
         </requestFiltering>
      </security>
   </system.webServer>
</configuration>

Note: You may also need to change this value in the registry .

That all said, the preferrable solution is to change how you're submitting these data. As you can see, you can POST nearly 30MB of data without changing the default configuration, which I imagine will be more than enough for your needs.

Obviously, this requires changing both your JavaScript (to use HTTP's POST method) and potentially your ASP.NET Core application (to ensure it will accept a [HttpPost] request).

Note: The exact limits will vary by web server software. But they're generally within this ballpark.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM