Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

120
Visualizações
Bad Request When Using PostAsJsonAsync C#

I am trying to Post a model to my MongoDB, but my Blazor app's post command does not even reach my API's Post method in the Controller. I've seen some topics about this and also tried to debug this issue for hours.

I am trying to post a really simple model.

public string MomentCategoryName { get; set; }

The button click activates this method. (I hardcoded a CategoryName for this one.)

public async Task PostAsync(MomentCategoryModel momentCategory)
        {
            using (HttpResponseMessage response = await _api.ApiClient.PostAsJsonAsync("api/MomentCategory/Create", momentCategory))
            {
                if (!response.IsSuccessStatusCode)
                {
                    throw new Exception();
                }
            }
        }

The baseuri and the client is initialized in another class, but the whole uri will look like this: https://localhost:7141/api/MomentCategory/Create

The PostMomentCategory in the MomentCategoryController gets a MomentCategoryModel from another library:

[BsonId]
[BsonRepresentation(MongoDB.Bson.BsonType.ObjectId)]
public string Id { get; set; }
public string MomentCategoryName { get; set; }

And then in the this code should run, but the compiler never gets to this, it never runs:

[HttpPost]
[Route("Create")]
public void PostMomentCategory(MomentCategoryModel model)
{
    _momentCategoryData.CreateMomentCategory(model);
}

Because of that I get back a Bad Request. But when I do a GET request that almost the same, it runs correctly. Example:

public async Task<List<MomentCategoryModel>> GetAllAsync()
        {
            using (HttpResponseMessage response = await _api.ApiClient.GetAsync("api/MomentCategory/GetAll"))
            {
                if (response.IsSuccessStatusCode)
                {
                    var result = await response.Content.ReadFromJsonAsync<List<MomentCategoryModel>>();
                    return result;
                }
                else
                {
                    throw new Exception();
                }
            }
        }

Thank you for your help and your time in advance!

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

For the json post you need a frombody option

public void PostMomentCategory([FromBody] MomentCategoryModel model)
over 4 years ago · Santiago Trujillo Relatório

0

You can try PostAsync method to POST your Model to your api endpoint. You can do this:

public async Task PostAsync(MomentCategoryModel momentCategory)
{
    string jsonData = JsonConvert.SerializeObject(momentCategory);
    StringContent content = new StringContent(jsonData, Encoding.UTF8, "application/json");
    using (HttpResponseMessage response = await _api.ApiClient.PostAsync("api/MomentCategory/Create", content))
    {
        if (!response.IsSuccessStatusCode)
        {
            throw new Exception();
        }
    }
}

And in your API method, you need to add [FromBody] attribute to get your posted data:

public void PostMomentCategory([FromBody]MomentCategoryModel model)
over 4 years ago · Santiago Trujillo Relatório

0

In MomentCategoryController I adjusted the Post method as the following:

[HttpPost]
[Route("Create")]
[Consumes("application/x-www-form-urlencoded")]
public void PostMomentCategory([FromForm] TestMCategoryModel model)
{
    _momentCategoryData.CreateMomentCategory(model);
}

In public async Task PostAsync(MomentCategoryModel momentCategory) method I added a list of KeyValuePair with one element. And also added an HttpContent like this: HttpContent httpcontet = new FormUrlEncodedContent();

This way it works, I get an OK code back (Status code 200). Maybe it would work with the suggested string content if I adjust what the API should consume. I will do a test with that as well, but right now it works this way.

I would like to thank everyone who took the time to read thru the issue and suggest a possible solution!

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda