Receiving a "Bad Request" error when trying to access a website

Every time I attempt to call a lengthy URL, I encounter a Bad Request issue.

https://localhost:44320/RespostaEmail/96635/750396/[%7B%22IdItem%22:8,%22IdTipoReposta%22:80%7D,%7B%22IdItem%22:1,%22IdTipoReposta%22:80%7D,%7B%22IdItem%22:3,%22IdTipoReposta%22:80%7D,%7B%22IdItem%22:2,%22IdTipoReposta%22:80%7D,%7B%22IdItem%22:5,%22IdTipoReposta%22:80%7D,%7B%22IdItem%22:7,%22IdTipoReposta%22:80%7D,%7B%22IdItem%22:10,%22IdTipoReposta%22:80%7D,%7B%22IdItem%22:4,%22IdTipoReposta%22:80%7D,%7B%22IdItem%22:6,%22IdTipoReposta%22:80%7D,%7B%22IdItem%22:9,%22IdTipoReposta%22:80%7D]

Each time the JavaScript function is called, it redirects me to this URL

function responder(idDivergencia, numGF, dia, mes, ano) {
let observacao = $('#observacao').val();

if (observacao.trim() == '') {
    abrirDialogAlertaMensagem('Informe uma observação para visualizar a tela de resposta.');
    return;
}

while (observacao.indexOf('/') != -1) {
    observacao = observacao.replace('/', '-')
}

var lista = ObterListaDeItens(idDivergencia, numGF);
var itens;

if (lista != null) {

    $('.btnSalvarDiv').click();
    itens = JSON.stringify(lista);

    window.location.href = RELATIVE_PATH + 'RespostaEmail/' + idDivergencia + '/' + numGF + '/' + itens
} else {
    abrirDialogAlertaMensagem('Informe o(s) tipo(s) de resposta para visualizar a tela de resposta.');
    return;
}

}

This is my controller code snippet

[HttpGet]
    [Route("RespostaEmail/{idDivergencia}/{numeroGf}/{itensDivergencia}")]
    public IActionResult RespostaEmail(int idDivergencia, int numeroGf, string itensDivergencia)
    {
        if (itensDivergencia == "favicon.ico")
            return View();

        var listaItems = JsonConvert.DeserializeObject<List<ItemResposta>>(itensDivergencia);

        var breadcrumb = BreadcrumbControl.GetInstance();
        breadcrumb.AddNewPage("Resposta Email", "Resposta", "RespostaEmail");

        var dados = new Resposta();
        var itens = _divergenciaAppService.ListarItensDivergencia(idDivergencia);

        foreach (var item in itens)
        {
            dados.ItemSolicitado.Add(new ItemSolicitado
            {
                CodigoDivergencia = item.CodDivergencia,
                IdGrupo = item.IdGrupo,
                IdItem = item.IdItem,
                Peca = item.PecaSolicitada,
                Quantidade = item.QtdDivergente ?? 0,
                TipoResposta = listaItems.FirstOrDefault(x => x.IdItem == item.IdItem).IdTipoReposta
            });
        }

        dados.IdDivergencia = idDivergencia;
        dados.NumeroGF = numeroGf;

        var email = _respostaAppService.MontarEmailResposta(dados);

        ViewBag.TextoPadrao = email;
        ViewBag.IdDivergencia = idDivergencia;
        ViewBag.Conta = ContaUsuario;
        ViewBag.IdGrupo = dados.ItemSolicitado.Select(x => x.IdGrupo).LastOrDefault();
        return View();
    }

I am attempting to adjust the maximum length but cannot locate where to configure this. My project is based on .NET Core 3.1 and has a Startup file, however, I am unable to identify the solution in that file. Any alternative approaches to resolving this issue would also be appreciated.

Answer №1

I encountered the issue on my own computer. Interestingly, I couldn't replicate it in a local environment as I received a 200 response on localhost. The problem only arises on the IIS server. Despite trying different browsers, the issue persisted. Upon testing with a shorter URL, it worked fine, indicating that the problem lies with the length of the URL and is likely due to server limitations. To address this, we can modify the webserver configuration in the web.config file,

<configuration>
  <location path="." inheritInChildApplications="false">
    <system.webServer>
      <handlers>
        <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
      </handlers>
    <security>
          <requestFiltering>
              <requestLimits maxAllowedContentLength="30000000" maxUrl="30000000" maxQueryString="30000000" />
          </requestFiltering>
        </security>
      <aspNetCore processPath="dotnet" arguments=".\WebApplication1.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" hostingModel="inprocess" />
    </system.webServer>
    <system.web>
          <httpRuntime maxRequestLength="999999999" maxQueryStringLength="2097151" maxUrlLength="2097151" />
    </system.web>
  </location>
</configuration>

This configuration snippet gets automatically added to the root directory when using IIS 10, increasing the URL length limit. However, this solution did not prove effective and is not recommended as long URLs can lead to increased response times and other issues.

View response time of long URL here https://i.sstatic.net/43KWb.png

View response time of short URL here https://i.sstatic.net/eccJU.png

To mitigate this issue, one simple solution is to switch from using the GET method to a POST method. By including part of the request in the body, it ensures a safer and more efficient transfer of data. Simply write the necessary JavaScript in a .js file and update the Action to utilize an httpPost method.

.js

function responder(idDivergencia, numGF, dia, mes, ano) {
...
var httpRequest = new XMLHttpRequest();
httpRequest.open('POST');
httpRequest.setRequestHeader("Content-type", "application/json");

if (lista != null) {
    …

    window.location.href = RELATIVE_PATH + 'RespostaEmail/';
    var body = idDivergencia + '/' + numGF + '/' + itens
    httpRequest.send(body);
    httpRequest.onreadystatechange = function () {
    …
    }
} else {
    ...
}

}

Controller

[HttpPost]
[Route("RespostaEmail")]
public IActionResult RespostaEmail(int idDivergencia, int numeroGf, string 
itensDivergencia)
{
…
}

See the response here

https://i.sstatic.net/GjF95.png

Answer №2

By utilizing a query string, I successfully resolved this issue without encountering the problem of a large URL.

I made adjustments to my JavaScript code:

function responder(idDivergencia, numGF, dia, mes, ano) {
...

var queryString = '?idDivergencia=' + idDivergencia + '&numeroGf=' + numGF + '&itensDivergencia=' + itensCodificado;

window.location.href = RELATIVE_PATH + 'RespostaEmail/' + queryString

...
}

and updated my controller as follows:

[HttpGet]
[Route("RespostaEmail")]
public IActionResult RespostaEmail(int idDivergencia, int numeroGf, string itensDivergencia)
{
...
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to send additional data with getServerSideProps() in Next.js?

Not sure if this is a silly question, but I am currently working with a Django API and attempting to implement pagination on the search page using Next.js. As a newbie to Next.js, I have scoured the web for a solution but haven't found anything helpfu ...

Trouble fetching data for my controller in AngularJS using UI Router resolve

My attempts to inject a resolve object containing loaded data into my controller are resulting in an Unknown Provider error : Error message: Unknown provider: configServiceProvider <- configService Below is the code I am working with: StateProvider ...

Unable to Achieve Full Height with Vuetify Container

Challenge: I'm facing an issue with my <v-container> component not consistently spanning the entire height of the application. Despite trying various methods such as using the fill-height property, setting height: 100%;, height: 100vh;, and expe ...

Specify the versions of packages in your package.json file

My package.json file contains many dependencies with "*" as the version, which I have learned is not recommended. I want to update them all to their latest versions. Despite using npm-check-updates tool, it indicates that all packages are up-to-date. Can ...

Guide on populating a textbox with values through Ajax or Jquery

Consider the scenario where there are three textboxes. The first textbox requires an ID or number (which serves as the primary key in a table). Upon entering the ID, the semester and branch fields should be automatically filled using that ID. All three fie ...

Canvas - Drawing restricted to new tiles when hovered over, not the entire canvas

Imagine having a canvas divided into a 15x10 32-pixel checkerboard grid. This setup looks like: var canvas = document.getElementById('canvas'); var context = canvas.getContext('2d'); var tileSize = 32; var xCoord var yCoord ...

Customized selection groups for dropdown menu based on alphabetical order

I am dynamically generating a select list from an array of data and I want to group the options alphabetically. For example, here is the data: data = [ ['bcde','21254'], ['abcd','1234'], ['abcde',' ...

Guide to showcasing a placeholder in MUI's Select component

How can I add the placeholder "Select a brand" to this select element? I've tried different options with no luck. Here is the code snippet I am working with: <FormControl fullWidth> <InputLabel id="demo-multiple-name-label" ...

Sending Data via Ajax

I am currently working on implementing an ajax invitation script that allows users to invite their friends to an event. The javascript code I have used in other parts of the website works perfectly, but for some reason, it is not functioning correctly in t ...

Arrange four Divs next to each other with flexbox styling

I've been struggling with aligning my cards side by side. They are a series of divs nested in lists under a <ul> Changing the positioning is not resolving the issue, and I'm hesitant to alter the display as it's crucial for responsive ...

JavaScript - Attempting to retrieve data using AJAX

Struggling with extracting data from an AJAX call using jQuery while implementing RequireJS for better maintainability and modularity in my JavaScript. Still new to RequireJS so not entirely sure if I'm on the right track. Just aiming to keep my JS mo ...

In the production mode, Webpack doesn't compile any code

I recently followed the typescript guide at https://webpack.js.org/guides/typescript/ After running webpack in "production" mode, I noticed that it emitted very minimal output. Below is the code from my src/index.ts file: export function foo() { return ...

Issue with the submission button not triggering onclick event correctly

I've been trying to add an onclick event to a submit button. I've searched various tutorial sites and followed all the suggestions, but none of them have solved the issue. Interestingly, when I include an alert in the function being called, it wo ...

Extracting specific attributes from an array to showcase on a single div

example: { "data": [ { "name": "banana", "color": "yellow" }, { "name": "kiwi", "color": "brown" }, { "name": "blueberry", "color": "blue" } ] } Instead of div, I want to use a span for each ...

Pressing the up arrow in Javascript to retrieve the most recent inputs

Is there a way to retrieve the most recent inputs I entered in a specific order? For example: I have an array with 20 elements, and every time I enter something, I remove the first element from the array and add the new input at the end. So, when I press ...

How can a loading circle be displayed upon clicking a button on a PHP website using JavaScript?

As a newcomer to the world of JavaScript programming, I'm facing a challenge that seems deceptively simple. My goal is to display a loading circle when a user clicks on an upload button, trigger external PHP code for image processing, and then make th ...

Utilize Ajax and Nodejs to inject dynamic content into your webpage

Seeking assistance in implementing a project where a navigation bar on the page contains various items, and I aim to display the content of each tab without reloading the entire page. Utilizing Nodejs with the ejs template engine, my research hasn't l ...

Exploring Design Patterns for CellPainting in DataGridView

Currently I am exploring Design Patterns in .NET. I am curious to know what type of Design Pattern is utilized in the CellPainting feature of DataGridView. In DataGridView, you have the option to specify the type of DataGridViewColumn you would like to us ...

A guide on sending arguments to a react function component from a JSX component via onClick event handling

Below is a brief excerpt from my extensive code: import React from "react"; const Home = () => { return ( imgFilter.map((imgs) => { return ( < Col sm = "3" xs = "12" key ...

Guide to downloading a CSV file directly from a webpage built with vue.js

Delving into the world of vue.js, I find myself pondering over how to incorporate a download link in my webpage for a CSV file stored locally. In my component Template.vue, I have the following structure: <a :href="item.loc" download> {{item.title ...