asp.net API post values received are null from postmaster - c#

I'm writing a very basic asp .net api with a simple post method. The post parameters are returning null. I've tried various ways to get the method to return the object I passed in. I created a data transfer object and I've verified that the method is getting called. What else can I check ?
post master settings ----
url: /api/values
params: incidentID 4
params: incidentTitle 'this is some text'
Content-Type: application/json
// POST api/values
[Route("api/values")]
[HttpPost]
public HttpResponseMessage Post([FromBody]incidentDTO incid)
{
return Request.CreateResponse(incid);
}

I assume by postmaster you meant Postman.
If you are using Postman, use the following steps:
Under Header type Content-Type with a value of application/json
Select the raw tab and enter your data as follows:
{
"incidentId":4,
"incidentTitle":"this is some text"
}
Click on Send.
As the post data is being read from the body, there in no need to enter any values in URL params.

Related

Is there a way in Postman to store multiple values for one key?

I am working on side-project using ASP.Net Core web api. I am currently using Postman so I can interact with custom middleware. As you can see in the picture I have a User id and would like the request header to have more than one value for the user id key. Everytime I debug the api, the request header only counts one value instead of two values. I have looked at the Postman help page but it doesn't really cover any material regarding my issue. So to condense my question, is there a way in Postman that a key (For my scenario, User Id) can hold more than one value.
Your question doesn't really make sense. Postman will send the data you put, to the server. The data you put is "1,2". At the server end, if you pull the userId value and split it on the comma, you have your two values, no?
I find it incredibly unlikely that when you pull userId at the server, the value of the header is "1" and the other id has disappeared. If the web did that loads of headers (such as your gzip, deflate, br there) would get lost and stuff wouldn't work properly
In java with spring boot framework i have idea about it we have to send List userIds from request controller method this method you have to take as post method and send that data into body part with
#PostMapping("/listUsers")
public String getList(#RequestBody List<Integer> userIds) {
// call service method
return "page";
}
Json Request from postman
{
1,2,3,4,5............
}
In dot net core
[Produces("application/json")]
[Route("api/accounts")]
public class AccountsController : Controller
{
[HttpGet]
[Route("servicesbycategoryids")]
public IActionResult ServicesByCategoryIds([FromQuery] int[] ids)
{
return Ok();
}
}

"400/The input was not valid" when calling ASP.NET Core Web API

I'm testing my Web API using postman and am getting back a "400 Bad Request" or "The input was not valid" in Postman. The break point on the first line of my action isn't getting hit. How can I figure out what's going on behind the scenes?
I would show a screenshot of Postman, but I can't get the image to upload. It's simply a POST with several fields specified for the Body. Here's the URL:
http://localhost:52126/api/v1/itinerary
Here's the action:
[HttpPost]
[Route("api/v1/itinerary")]
public async Task<ActionResult> AddItineraryAsync([FromBody] Itinerary itinerary)
{
if (!ModelState.IsValid) // Break point on this line not getting hit!
{
return BadRequest(ModelState);
}
await Logic.AddItineraryAsync(itinerary);
return Ok();
}
Originally, I didn't have [FromBody] specified for the action. It doesn't work either way. What can I check to figure out what's going on?
Clarification (in response to Chris Pratt):
I'm in the early stages of writing my first mobile app, and, being a bottom-up kind of guy, I'm getting some Web API calls working first. I assume I'll be passing JSON from the mobile app to this server layer.
I haven't done anything having to do with anti-forgery tokens in this Web API project, so I assume those aren't in play...unless that's something that's coming from Postman.
Removing the parameter from the action does allow the execution to fall through to my break point, so the error does seem to be with ASP.NET's attempt at binding.
After digging around in Postman a bit, I did see that the header was specifying x-www-form-urlencoded for the Content-Type. I changed it to application/json, as you suggested. However, that didn't seem to make a difference.
More Info:
After trying what Carl suggested below, I have more information. Execution dropped down into the action and I got a look at what is being passed from Postman. Here it is:
----------------------------179455694862693501539465
Content-Disposition: form-data; name="StartPoint"
Tacoma
----------------------------179455694862693501539465
Content-Disposition: form-data; name="EndPoint"
Portland
----------------------------179455694862693501539465
Content-Disposition: form-data; name="TravelDate"
2018-8-21 07:00:00 AM
----------------------------179455694862693501539465
Content-Disposition: form-data; name="Name"
Test Itinerary
----------------------------179455694862693501539465
Content-Disposition: form-data; name="UserAccountId"
2
----------------------------179455694862693501539465
Content-Disposition: form-data; name="Comment"
Just doin' some testing.
----------------------------179455694862693501539465--
The Json deserialization is failing with:
JsonReaderException: Input string '----------------------------179455694862693501539465' is not a valid number.
What are these numbers and where are they coming from?
ModelState is only validated if it's able to successfully deserialize the post body/bind.
You were not specific in your question, but it sounds as if you're posting as x-www-form-urlencoded. If that's the case, you should not have [FromBody]. However, bear in mind that it's an either/or situation, so if you want to eventually post via JSON, then you should keep the attribute and post JSON from Postman instead.
Aside from that, ensure that you're either not using antiforgery token validation or that you are posting a valid token along with the request. Failing antiforgery validation will short circuit the request and return a 400 immediately.
If you are posting JSON, ensure that your JSON is valid. If the JSON is invalid, you'll get a 400 immediately.
Solution From Comment:
For 179455694862693501539465, it seems you are using PostMan with application/x-www-form-urlencoded as Content-Type.
I suggest you follow steps:
1. keep your api with AddItineraryAsync([FromBody] Itinerary itinerary);
2.clear your headers in postman
3. Body tab choose raw with JSON(application/json)
4. enter valid json string or just with {}
5. make sure there is no additional headers except application/json as Content-Type in headers tab.
6. send request to check whether api method will be hit.
I was trying it like your [FromBody] Itinerary itinerary but got a work around. The 2.1 framework has Issues https://github.com/aspnet/Mvc/issues/7609 and https://github.com/aspnet/Mvc/issues/7799. I got this working in 2.1: client javascript is unchanged:
var payload = JSON.stringify({ "name": document.getElementById('firstname').value, "email": document.getElementById('email').value, "captcha": grecaptcha.getResponse() });
var oReq = new XMLHttpRequest();
oReq.ContentType = "application/json";
oReq.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("update").innerHTML = this.responseText;
}
else document.getElementById("update").innerHTML = "not 4&200! : " + this.responseText;
};
oReq.open('POST', 'api/u');
oReq.send(payload);
and the controller has:
[Route("api/[controller]")]
// [ApiController] // works either way
public class UController : ControllerBase
{
[HttpPost]
public async Task<string> signUp()
{
String body;
using (StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8))
{
body = await reader.ReadToEndAsync();
}
UserSignup user = JsonConvert.DeserializeObject<UserSignup>(body);
return user.email;
}
}
Soon to be on https://github.com/Hover-Us/

Processing Post Request from Slack

I've setup an asp.net MVC web application to capture post request. I've set breakpoints to see what info is coming through. When an interactive button is clicked, my breakpoint is hit but the object has no details. It simply says {Object} when i hover over value. When I use Postman and send a raw JSON body, it displays the JSON. May I ask how am i suppose to process the slack object that is sent?
public void Post(object value)
{
// breakpoint here
}
For interactive messages Slack send a standard POST request with a single form-data encoded parameter called payload in the body. This parameter contains the data of the actual request as JSON string.
You can simulate this with Postman by using the following parameters:
Request type: POST
Header: Content-Type: application/x-www-form-urlencoded
Body: form-data, with key=payload and value = JSON string.
So the body is not fully JSON as you assumed, but contains a form parameter with a JSON encoded string. If you change your app accordingly, it will work.
In c# you can access the content of the payload parameter with Request["payload"] (see this answer or details).
Then you still need to decode the JSON string into an object of course. An easy approach is to use JavaScriptSerializer.Deserialize. (see this answer for details and alternative approaches).

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.

WCF Data Services - Custom POST method

I have created a WCF Data Service and it works fine. My Custom methods that are GET type methods work ok as well. The problem is in POST custom method.
The method looks like that:
[WebInvoke(Method = "POST")]
public string CustomMethod(string myParameter)
{
return "yes" + myParameter;
}
I also invoke:
config.SetServiceOperationAccessRule("CustomMethod", ServiceOperationRights.All);
Then in fiddler my request looks like that:
Method: POST
URL: http://localhost:1219/DataService.svc/CustomMethod
Reguest Headers:
User-Agent: Fiddler
Host: localhost:1219
Content-Length: 27
Content-Type: application/x-www-form-urlencoded
Request Body:
myParameter=parameter1value
The method gets called but the "myParameter" parameter is always null. What am I missing?
Thanks for your time.
Please refer to Section 10.4.1.3. Invoking an Action for OData 3.
Short story: The content type must be JSON.
If the invoke request contains any non-binding parameter values, the
Content-Type of the request MUST be 'application/json', and the
parameter values MUST be encoded in a single JSON object in the
request body.
I believe the way you are passing parameter 'myParameter' may be wrong.
you can try to consume your service using visual studio and then try to pass it.
one more question..
when you call the service as get service, is Content-Type is
Content-Type:application/x-www-form-urlencoded

Categories