Reputation: 57
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!
Upvotes: 2
Views: 3059
Reputation: 25029
Wait!
Before you give up on PostAsJsonAsync
in favor of PostAsync
, know that serialization matters! You might be using (a mix?) of Newtonsoft.Json
and System.Text.Json
.
If your model looks like this:
using Newtonsoft.Json;
public class AddressRequest
{
[JsonProperty("state")]
public string State { get; set; }
[JsonProperty("street")]
public string Street { get; set; }
[JsonProperty("street_number")]
public string StreetNumber { get; set; }
You might be using the wrong attribute!
PostAsJsonAsync
uses System.Text.Json
and JsonPropertyName
!PostAsync
uses Newtonsoft.Json
and JsonProperty
!So try using JsonPropertyName
on your model class to serialize to the correct name!
In the example above, the code might be serializing to a name of StreetNumber
instead of street_number
, thus giving you a 400 bad request response.
Upvotes: 0
Reputation: 57
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!
Upvotes: 2
Reputation: 8302
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)
Upvotes: 2
Reputation: 43860
For the json post you need a frombody option
public void PostMomentCategory([FromBody] MomentCategoryModel model)
Upvotes: 0