Can't bind array - asp.net-core-webapi

[HttpPost("notify")]
public async Task<IActionResult> Notify([FromBody] int [] ids)
{
return Ok();
}
Request payload:
{ ids: [1, 2, 3]}
ids parameter is null.
If I change ids to type object, it's concret type is JObject.
What am I missing?

The payload in the question is an object with a property called ids, but the signature is for an array. Thus, I changed the Javascript to directly post an (anonymous) array...
axios.post("lalala", this.props.items.map(function (s) { return s.id }))

Related

returning OkNegotiatedContentResult does not do content nogotiation

In ASP.NET Web API (4.6.2) why wrapping response inside Ok does not do content negotiation?
For example
Http Request has the following headers:
Content-Type:application/json and
Accept:application/xml
and i have two methods
[HttpGet]
public IHttpActionResult GetData()
{
return Ok(new { FirstName = "foo", LastName = "bar" });
}
[HttpGet]
public Person GetData2()
{
return new Person { FirstName = "foo", LastName = "bar" };
}
The first method always returns response in Json format. It does not obey the Accept header. The return type of the Ok method is OkNegotiatedContentResult. Which as per the documentation
Represents an action result that performs content negotiation and
returns an HttpStatusCode.OK response when it succeeds
Second method GetData2, however, returns the correct response and obey the Accept header
Update 1
looks like Ok does not do content-negotiation with anonymous types.
if i do
return Ok( new Person(){FirstName="foo", LastName="bar"});
it works

How to return IEnumerable list of objects with WebApi?

I have an object called PostMapDB and a method which retrieves a list of those objects. I would like to be able to pass this list and retrieve the data using webapi.
The code bellow gets me an error:{"":["The input was not valid."]}
[HttpGet]
public string Get(PostMapDB list)
{
IEnumerable<PostMapDB> dataOfPosts = list.getAllPosts().OrderBy(x => x.Date);
var data = JsonConvert.SerializeObject(dataOfPosts, new JsonSerializerSettings()
{
ContractResolver = new DefaultContractResolver()
{
IgnoreSerializableAttribute = false
}
});
return data;
}
How does your request to server looks like?
What's the definition on PostMapDB?
Make sure you're passing data in a right way.
Probably the attribute FromBody would help:
public string Get([FromBody] PostMapDB list)
Reference: https://learn.microsoft.com/en-gb/aspnet/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

Firebase cloud firestore is storing document reference as string not as object reference

I have a collection campgrounds which should store the references of the comment documents as an array of object reference
I did it like this
try {
commentRef.add(newComment).then(ref => {
console.log("success COMMENT ADDED");
var refForThisComment = ref.id;
docRef.update({
comments: firebase.firestore.FieldValue.arrayUnion(
"/campgrounds/" + refForThisComment
)
});
res.redirect("/campgrounds");
});
} catch (error) {
res.send(error);
}
But in the console when I check the document reference array is a string array!
You're seeing a string array because you passed a string to arrayUnion:
"/campgrounds/" + refForThisComment
This doesn't just become a document reference. String concatenation always produces a string in JavaScript.
If you want a document reference, pass a DocumentReference object instead:
comments: firebase.firestore.FieldValue.arrayUnion(ref)

Convert an api result set to a c# Object

I am calling an API to get a set of assignment data as JSON. I would like to convert that into C# model objects and display the results in my MVC view. Here is my code so far that successfully brings back the results, now I need it converted to an assignment Model (i.e I need API response.content turned into assignment).
[HttpGet]
public async Task<ViewResult> Index()
{
if (!ModelState.IsValid)
{
return View("Error");
}
HttpRequestMessage apiRequest = CreateRequestToService(HttpMethod.Get, "api/Assignment/GetAll");
HttpResponseMessage apiResponse;
Assignment assignment = new Assignment();
try
{
apiResponse = await HttpClient.SendAsync(apiRequest);
}
catch
{
return View("Error");
}
if (!apiResponse.IsSuccessStatusCode)
{
return View("Error");
}
var result = apiResponse.Content.ReadAsStringAsync();
var results = ???
return View( results);
}
I need API response.content turned into assignment
Convert the content of the response to the desired type. Lets assume it is a collection of the models
//...
var assignments = await apiResponse.Content.ReadAsAsync<List<Assignment>>();
//...

IHttpActionResult difference between returning item, Json(item) and Ok(item)

In ASP.NET WebApi 2, what is the difference between the following:
public <IHttpActionResult> GetItem(Guid id)
{
// ... code ..., Item result = ....
return result;
}
public <IHttpActionResult> GetItem(Guid id)
{
// ... code ..., Item result = ....
return Json(result);
}
public <IHttpActionResult> GetItem(Guid id)
{
// ... code ..., Item result = ....
return Ok(result);
}
This code returning result won't compile, as result doesn't implement IHttpActionResult...
public <IHttpActionResult> GetItem(Guid id)
{
// ... code ..., Item result = ....
return result;
}
Returning Json() always returns HTTP 200 and the result in JSON format, no matter what format is in the Accept header of the incoming request.
public <IHttpActionResult> GetItem(Guid id)
{
// ... code ..., Item result = ....
return Json(result);
}
Returning Ok() returns HTTP 200, but the result will be formatted based on what was specified in the Accept request header.
public <IHttpActionResult> GetItem(Guid id)
{
// ... code ..., Item result = ....
return Ok(result);
}
Just an addition to previous explanations:
The return types for your fuctions are: IHttpActionResult
Therefore the expectation is for the method to return a IHttpActionResult which is an interface for HttpResponseMessage. The HttpResponseMessage has useful properties such as Headers, Content, and Status code.
Therefore, Ok(result) returns a HttpResponseMessage with Ok status code and the contents, which in this case is the result. Meanwhile, Json(result) converts the object to json format, aka serialization, and that gets placed as the content in the HttpResponseMessage.
The best thing about a web api with ASP.NET is that it creates simple ways to pass the Http Responses through abstraction. The worst thing, is it takes a bit of understanding before actually using the relatively simple methods.
Here is more info about serilization and json
Here is more about info about IHttpActionResult

Resources