How do you provide frombody data to webapp - asp.net-mvc

I'm looking at somebody else webapp written in asp.net and it has a post request handler with this prototype
public class NotificationsController : ApiController
{
public async Task<HttpResponseMessage> Post(string pns, [FromBody]string message, string to_tag)
.....
.....
I'm testing that post request handler with postman (Chrome extension) and providing pns and to_tag as url parameters. But how do I provide message parameter? I tried setting content-type as json and provide message in body as
{ "message" : "hello"} OR { "body" : "hello" }
But I'm getting 500 error code.

It kind of depends on what version of Postman you are using. But you will put your JSON in the Body tab and choose the 'raw' radio button also on the Body tab.
You will want to set the Content-Type header to application/json. If you are still having issues, please add an image to your question of the Postman screen.
You will want to use: { "message" : "hello"} for the body message.
Finally, the pns and to_tag parameters should probably also be given [FromUri] annotations so it is more clear that they are to be passed in as URL Parameters.

Related

how to add a status message on a grails respond

I have created a method that is called after every uncatched exception and respond a gson view:
void handleError(){
respond([status: 500, view: "/customErr"], [
code : 500,
message : "whatever internal error",
])
}
this works fine but the main problem that I have is that my client (another server acting as client) is receiving a http response with a 500 status but the status message is null. I've checked the respond docs and I don't see a property message or something.
this if what my client receive:
wslite.rest.RESTClientException: 500 null
and that null is the response's status message that is not set by grails
How can I add a detail message on my respond? idyllically something like this:
respond([status: 500, statusMessage: "my custom
message", view: "/customErr"], [
code : 500,
message : "whatever internal error",
])
grails uses Servlet API’s HttpServletResponse to build response.
now check the java doc for HttpServletResponse class.
there are only 2 methods to define status message:
void setStatus(int sc, String msg) Deprecated. As of version 2.1, due to ambiguous meaning of the message parameter. To set a status code use setStatus(int), to send an error with a description use sendError(int, String).
void sendError(int sc, String msg) Sends an error response to the client using the specified status and clears the buffer. The server defaults to creating the response to look like an HTML-formatted server error page containing the specified message, setting the content type to "text/html".
The first one is deprecated. The second one sends the status message, but it will not send the body - mainly this used for fatal errors...
So, officially by servlet documentation there is no way to send both: message and body in response.
The question is tricky. Because according to Apache Tomcat the "custom status message" feature will be removed starting from version 9: https://tomcat.apache.org/tomcat-8.5-doc/config/systemprops.html#Other
But according to RFC2616 sec 6.1.1 : The reason phrases listed here are only recommendations -- they MAY be replaced by local equivalents without affecting the protocol.
This doesn't directly answer your question, and may not solve your issue depending on how much control you have over the application that receives the error, but you can add error messages to the header of the response which should pass through to the client (if it knows to check for them).
String errorMessage = "Whatever Internal Server Error"
response.addHeader("custom-error", errorMessage)
response.sendError(500, errorMessage)
That'll send the message in the header and as the response message... I do not know if this works with respond() or how that interacts with the response object in the controller... but if you're responding to render a view as the error page, you should be able to add the message to the model included in the respond() call and show that on the error page (at least, I'd think so).

Rest Assured :- Getting 404 response from Post request created using Pathparam and FormParam

I am a newbie to Rest Assured and need your help on the following issue.
I want to trigger a POST request which is as follows:-
Response resp = RestAssured.given().pathParam("build", bulid).
formParam("file", "https://unsplash.com/photos/Bcv4wZSMtIA").// Cast
formParam("type", "front").
formParam("auto_start", false).
then().post("https://example.com/{build}");
Where build= abc/xyz
Thus. should result in https://example.com/abc/xyz as endpoint and body as:
{
"file" : "https://unsplash.com/photos/Bcv4wZSMtIA",
"type" : "front",
"auto_start" : false
}
But when triggered it gives 404, whereas when instead of using pathparam I hardcode the value of build in post request then it works fine.
Can someone please advise what am I doing wrong here.
Found out that the url was being encoded when sent as request uri which when disabled using used urlEncodingEnabled(false) resolved my issue.

How to test 404 json response on ZF2

Considering that in my Zend Framework module I'm able to access via browser or REST. When I got a 404 via REST, this is the content:
{"httpStatus":404,"title":"Not Found"}
So how do I test this response using PHPUnit?
I have already a test for another route that is working:
public function testIndexActionCanBeAccessed()
{
$this->dispatch('/ws/dashboard');
$this->assertResponseStatusCode(200);
$this->assertModuleName('Ws');
$this->assertControllerName('Ws\Controller\Dashboard');
$this->assertControllerClass('DashboardController');
$this->assertMatchedRouteName('application/ws');
}
But I don't know how to do this other case.
public function testIndexActionCanBeAccessed()
{
$this->dispatch('/ws/asd');
$this->assertResponseStatusCode(404); // this is OK
// but how check the json response?
}
Also, if I do this $response = $this->getResponse(); I got the entire HTML 404 html file, which is not what I want.
You may want to check to ensure that the controller is actually returning a JSON response.
Also, your Accept header for the AJAX request should specify application/json.

Post Method with NSDictionary Values using Swift

I'm completely new toSwift. I need to hit a Post Method webservice with NSDictionary parameters & get the JSON response. I tried usingAlamofire & also NSMutableUrlRequest. Nothing seems to workout for me. I either get 'JSON text did not start with array or object and option to allow fragments not set' error or 'Undefined Variable' response from the server. The same service works fine when I try using Objective-C. As I said earlier, I am completely new toSwift & need your assistance.
My base url: http://myofficeit.in/bizfeed/webservices/client.php
Parameter I wanna Pass:
Parameter =
{
UserName = xyz;
deviceModel = iPhone;
deviceToken = "949264bc cd9c6c851ee64cc74db9078770dd7d971618ec20ce91d2e6eb9f155e";
emailid = "xyz#gmail.com";
location = Asia;
userMobileNo = 1234567890;
};
functionName = register;
The code I used for hitting the service is: http://pastebin.com/aaT4uhS7
Thanks
you can use like
let param: [String:AnyObject] = [
"UserName": iPhone,
"deviceToken": "949264bc cd9c6c851ee64cc74db9078770dd7d971618ec20ce91d2e6eb9f155e",
"emailid": "xyz#gmail.com",
"location": Asia,
"userMobileNo": 1234567890
]
Alamofire.request(.POST, "http://myofficeit.in/bizfeed/webservices/client.php/register", parameters: param).responseJSON { (req, res, json, error) in
print(req)
print(res)
print(json)
print(error)
}
for sample request in Alamofire
As broad as your question is, the broad will be my answer:
The first thing to do, is to get a clear idea about the web service API, which also requires a basic knowledge of the HTTP protocol. So, what you need to understand is, what the server expects in HTTP terminology.
You eventually will find out, how the server will expect its "parameters". Note, that there is no term like "parameters" in the HTTP protocol. So, you need to map them into something the HTTP protocol provides.
Most likely, in a POST request, "parameters" are transferred as the body of the HTTP message, as a content-type which is application/x-www-form-urlencoded, multipart/form-data or application/json.
According to the needs of the server, and with your basic knowledge of HTTP and NSURLSession, NSURLComponents etc., you compose the URL and the body of the request, set Content-Type header and possibly other headers and you are ready to go.
How this eventually looks like is given in the answer of #AnbyKarthik, which used Alamofire, and a command that composes a POST request whose parameters are send in the body whose content-type is x-www-form-urlencoded.

Proxying MultiPart form requests in Grails

I have a Grails controller that receives a DefaultMultipartHttpServletRequest like so:
def myController() {
DefaultMultipartHttpServletRequest proxyRequest = (DefaultMultipartHttpServletRequest) request
}
This controller acts as a proxy by taking pieces of this request and then resends the request to another destination.
For non-multipart requests, this worked fine, I did something like:
IProxyService service = (IProxyService) clientFactory.create()
Response response = service.doPOST(proxyRequest.getRequestBody())
Where proxyRequest.getRequestBody() contains a JSON block containing the request payload.
However, I do not know how to get this to work with multipart request payload, since the request body is no longer a simple block of JSON, but something like the following (taken from Chrome devtools):
How can I can pass this request payload through using my proxy service above, where doPost takes a String?
Have you tried
def parameterValue = request.getParameter("parameterName")
to get the parameter value?
If you see the method signatures for DefaultMultipartHttpServletRequest you will see there are methods for getting the files and other parameters separately because the request body is getting used to both upload the file and to pass in other parameters.

Resources