Dynamic model binding with ASP.NET WEB API - c#

According to Scott Hanselman, on his blog, I should be able to do dynamic model binding and return a dynamic.
I have a Web API controller that contains a single method:
public dynamic Post(dynamic data)
{
return data;
}
When I make the following call from Fiddler, I am getting a null returned.
POST http://localhost:57856/api/values HTTP/1.1
User-Agent: Fiddler
Host: localhost:57856
Content-Type: "application/json"
Content-Length: 22
{"Name": "jlucpicard"}
What am I missing here? Shouldn't it return JSON for data? This is a simpler follow-up to my original question ASP.NET WEB API not binding to dynamic object on POST.

Your action is returning null because your "data" parameter is not being bound to the incoming json data.
Remove the quotes from "application/json" in your Content-Type header to bind to the data.
Content-Type: application/json

Related

Microsoft graph api create folder using path returning 'invalidRequest'

The following error is returned by graph api:
"error": {
"code": "invalidRequest",
"message": "[child] A null value was found for the property named 'id', which has the expected type 'Edm.String[Nullable=False]'. The expected type 'Edm.String[Nullable=False]' does not allow null values.",
"innerError": {
"request-id": "36d65bbb-2f6e-485c-b2b9-5bb7fdb76d19",
"date": "2017-09-30T00:24:06"
}
}
The code I'm using:
var url = "https://graph.microsoft.com/v1.0/me/drive/root:/joba:/children";
var folder = new ItemResource { name = "nested", folder = new FolderFacet() };
var response = api.PostAsJsonAsync<ItemResource>(url, folder).Result;
response.ThrowWhenUnsuccessful();
return response.Content.ReadAsAsync<ItemResource>().Result;
That is, I'm trying to create a nested folder named nested in the joba folder (which is inside root).
It doesn't work... I even tried to escape the colon :joba: but it doesn't work either. The same request works just fine in graph-explorer
What is wrong with mine?
EDIT
Fiddler request
POST https://graph.microsoft.com/v1.0/me/drive/root:/wdg:/children HTTP/1.1
Accept: application/json
Authorization: Bearer <OMITED>
Content-Type: application/json; charset=utf-8
Host: graph.microsoft.com
Content-Length: 268
Expect: 100-continue
Connection: Keep-Alive
{"id":null,"createdBy":null,"createdDateTime":null,"eTag":null,"cTag":null,"description":null,"lastModifiedBy":null,"lastModifiedDateTime":null,"name":"85923635-56af-4902-82da-babd95165c6b","parentReference":null,"webUrl":null,"folder":{"ChildCount":null},"file":null}
PostAsJsonAsync uses Json.NET under the covers, which by default will serialize properties with null values. Since omitting a value is treated differently to deliberately specifying a null value, when this occurs it triggers the OneDrive API to consider the request invalid, because a null value is specified for a non-nullable field.
To get around this you can add the following attribute to the nullable properties on the ItemResource type:
[JsonProperty(NullValueHandling=NullValueHandling.Ignore)]
Alternatively, you could use Json.NET to directly serialize the object and provide an appropriately configured JsonSerializerSettings instance, followed by a call to PostAsync.

ASP.NET Web API 2.0 Parameters Null

I know it's been asked a lot of time and I have tried everything but still facing the problem. Here is my code:
// POST api/<controller>
public string Post([FromBody]string value)
{
return value;
}
There is nothing fancy just returning the value.
I am using Chrome's PostMan Plugin
I have tried like 100 times but still getting the same null value as the response. I have tried it with Content-Type application/json and everything mentioned but still getting null.
Not really sure what the question is however what you are looking for is to setup your POST with a single value.
Such as below:
POST /api/values HTTP/1.1
Host: localhost:50121
Content-Type: application/json
Accept: application/json, text/javascript
Cache-Control: no-cache
'abc'
Now this is a JSON post so the body doesn't have a parameter name, this is by design as you are posting a single value.
If you need multiple values or a more complex object you should use a class object instead of a single value.

Null parameter in OData Custom Action

I want a custom action added in my OData controller for adding an entity. I can do that in standard Post method supplied in OData controller but I have some custom code that get's overwritten when I refresh the controller from database if I add an association.
Here is the custom method I've added
[HttpPost]
public IHttpActionResult CreateValidCombination(ValidCombination validCombination)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
return Ok();
}
The request header is same as the standard post method
POST http://localhost:20152/Admin/odata/ValidCombinations/fn.CreateValidCombination HTTP/1.1
Accept: */*
Content-Type: application/json
Referer: http://localhost:20152/Admin/index.html
Accept-Language: en-CA,en;q=0.5
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko
Connection: Keep-Alive
Content-Length: 284
DNT: 1
Host: localhost:20152
Pragma: no-cache
The Action is configured in WebApiConfig.cs as
builder.EntityType<ValidCombination>().Collection
.Action("CreateValidCombination")
.Returns<IHttpActionResult>();
The problem is while the standard OData Contoller Post method receives the parameter of type "ValidCombination" proper, customer method receives it as null.
I've checked request headers and body in fiddler and its same in both the cases. I've even tried putting [FromBody] in front of the parameter but to no avail. I am trying to get value into the parameter for my custom method.
Has anyone faced this situation before. Is there a way I can debug why the parameter is not properly being deserialized even though request and body are same for both the methods?
According to http://odata.github.io/WebApi/#04-07-action-parameter-support, in your customized action method, parameter type should be ODataActionParameters instead of ValidCombination, OData WebApi's code is in github, is very easy to debug, you can find lots of function tests too.

How Do I Pass Json Object From Fiddler To Webapi2

http://localhost:15641/api/Complaints/NewComplaint
User-Agent: Fiddler
Content-Type: application/json
Host: localhost:15641
Content-Length: 63
RequestBody
{
"CostCentre":"test","ComplaintText":"This is test Complaint"
}
WebApi Controller
[Route("api/Complaints/NewComplaint")]
[HttpPost]
public void CreateNewComplaint(BLL.Complaint complaint)
{
//call BLL Create complaint method
}
}
my object is with null values
where am i doing wrong ?
i put breakpoints on controller the complaint object is set with all null values
if i don't pass the values complaint object it self is null
how can i pass the object
Web API expects the data sent to it to be serialized in a fashion like this:
Key1=Value1&Key2=Value2&...
If you are using JavaScript or JQuery, make sure that you're sending an Object(in your case matching Bll.Complaint), not a JSON string. If you give us more details on how you execute the request I will update this answer to have an example of how to do the serialization.

WebAPI passed post parameters is null

I'm testing with WebAPI 2 and I have created the following controller method.
// POST api/values
public string Post([FromBody] string value)
{
string returnValue = "Return: " + value ;
return returnValue;
}
When i'm posting the following message with fiddler the method parameter keep returning null.
POST http://localhost:50814/api/Values/ HTTP/1.1
Host: localhost:50814
Content-Type: application/json
Content-Length: 14
{value: "New"}
I have simplyfied my code already as much as i can but still it stays null.
I think I'm overlooking something very simple but i'm out of ideas. Could someone please help me?
Thanks Sander
If you're taking a simple String from your Controller's Post method, try sending just this:
POST http://localhost:50814/api/Values/ HTTP/1.1
Host: localhost:50814
Content-Type: application/json
Content-Length: 10
"MyString"

Categories