I have been struggling with this the past few days. I have researched the issue and tried the solutions posted. However it has not worked. I have REST WCF Post method that has
[OperationContract(Name = "ImportRawJson")]
WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest,
ResponseFormat = WebMessageFormat.Json, RequestFormat=WebMessageFormat.Json,
UriTemplate = "ImportRawJson/username/{username}/password/{password}/fileName/{fileName}")]
string ImportRawJson(string username, string password, string fileName, string jsonStream);
I am able to consume this through web client. However when I try calling through Fiddler like below the body parameter always results in null and I get an exception.
Fiddler :
Post http://localhost/TimesheetService/Timesheet.svc/ImportRawJson/username/user/password/pwd/fileName/testfiddler
Request Headers:
User-Agent: Fiddler
Host: localhost
Content-Length: 32
Content-Type: application/json; charset=utf-8
Request Body:
{ "jsonStream":{ "ImportRaw": {"TestXml": {"xml": "test" } }}}
Error:
HTTP/1.1 400 Bad Request
Cache-Control: private
Content-Length: 127
Content-Type: application/json; charset=utf-8
Server: Microsoft-IIS/7.5
X-AspNet-Version: 4.0.30319
Set-Cookie: ASP.NET_SessionId=wh4qxcu1x0vmiv45mmzuuaup; path=/; HttpOnly
X-Powered-By: ASP.NET
Date: Tue, 07 May 2013 14:00:58 GMT
{"ErrorCode":"Error","Message":"Procedure or function expects parameter 'jsonStream', which was not supplied."}
Any help as to how I can pass the body parameter. I truly appreciate. I am stuck at this point. Please help!! Thanks in advance
There are a couple of issues in your code. First, if by "JSON stream" you mean any JSON document, you won't be able to use the type string for your code. Instead, you'll need to take it as a Stream (which can basically accept any arbitrary input). If you take the input as a string, you should pass a JSON string to it. And since you set the body type to WrappedRequest, you need to wrap the JSON string in an object, with the parameter name being the member name, and the value you want to pass to your function the value. For example, to pass the string hello world to your operation, you'd need to pass this request body:
{"jsonStream":"hello world"}
But if I guessed correctly, and you want to take any arbitrary JSON, you need to go with the Stream parameter. The blog post at http://blogs.msdn.com/b/carlosfigueira/archive/2008/04/17/wcf-raw-programming-model-receiving-arbitrary-data.aspx has more information about how to implement it.
Related
I'm using Hyper to send HTTP requests, but when multiple cookies are included in the response, Hyper will combine them to one which then fails the parsing procedure.
For example, here's a simple PHP script
<?php
setcookie("hello", "world");
setcookie("foo", "bar");
Response using curl:
$ curl -sLD - http://local.example.com/test.php
HTTP/1.1 200 OK
Date: Sat, 24 Dec 2016 09:24:04 GMT
Server: Apache/2.4.25 (Unix) PHP/7.0.14
X-Powered-By: PHP/7.0.14
Set-Cookie: hello=world
Set-Cookie: foo=bar
Content-Length: 0
Content-Type: text/html; charset=UTF-8
However for the following Rust code:
let client = Client::new();
let response = client.get("http://local.example.com/test.php")
.send()
.unwrap();
println!("{:?}", response);
for header in response.headers.iter() {
println!("{}: {}", header.name(), header.value_string());
}
...the output will be:
Response { status: Ok, headers: Headers { Date: Sat, 24 Dec 2016 09:31:54 GMT, Server: Apache/2.4.25 (Unix) PHP/7.0.14, X-Powered-By: PHP/7.0.14, Set-Cookie: hello=worldfoo=bar, Content-Length: 0, Content-Type: text/html; charset=UTF-8, }, version: Http11, url: "http://local.example.com/test.php", status_raw: RawStatus(200, "OK"), message: Http11Message { is_proxied: false, method: None, stream: Wrapper { obj: Some(Reading(SizedReader(remaining=0))) } } }
Date: Sat, 24 Dec 2016 09:31:54 GMT
Server: Apache/2.4.25 (Unix) PHP/7.0.14
X-Powered-By: PHP/7.0.14
Set-Cookie: hello=worldfoo=bar
Content-Length: 0
Content-Type: text/html; charset=UTF-8
This seems to be really weird to me. I used Wireshark to capture the response and there're two Set-Cookie headers in it. I also checked the Hyper documentation but got no clue...
I noticed Hyper internally uses a VecMap<HeaderName, Item> to store the headers. So they concatenate the them to one? Then how should I divide them into individual cookies afterwards?
I think that Hyper prefers to keep the cookies together in order to make it easier do some extra stuff with them, like checking a cryptographic signature with CookieJar (cf. this implementation outline).
Another reason might be to keep the API simple. Headers in Hyper are indexed by type and you can only get a single instance of that type with Headers::get.
In Hyper, you'd usually access a header by using a corresponding type. In this case the type is SetCookie. For example:
if let Some (&SetCookie (ref cookies)) = response.headers.get() {
for cookie in cookies.iter() {
println! ("Got a cookie. Name: {}. Value: {}.", cookie.name, cookie.value);
}
}
Accessing the raw header value of Set-Cookie makes less sense, because then you'll have to reimplement a proper parsing of quotes and cookie attributes (cf. RFC 6265, 4.1).
P.S. Note that in Hyper 10 the cookie is no longer parsed, because the crate that was used for the parsing triggers the openssl dependency hell.
When I make a request in RestSharp like so:
var response = client.Execute<bool>(request);
I get the following error:
"Unable to cast object of type 'System.Boolean' to type 'System.Collections.Generic.IDictionary`2[System.String,System.Object]'."
This is complete HTTP response, per Fiddler:
HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/7.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Mon, 01 Apr 2013 15:09:14 GMT
Content-Length: 5
false
It appears that everything is kosher with the response, so what gives?
Also, if I'm doing something stupid with my WebAPI Controller by returning a simple value instead of an object and that would fix my problem, feel free to suggest.
RestSharp will only deserialise valid json. false is not valid json (according to RFC-4627). The server will need to return something like the following at the least:
{ "foo": false }
And you'll need a class like to following to deserialize to:
public class BooleanResponse
{
public bool Foo { get; set; }
}
have created simple Restful service for log in verification. Following are my interface and class definitions.
Interface IDemo:
public interface IDemo
{
[OperationContract]
[WebInvoke(RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare,
UriTemplate = "/ValidateUser?Username={UserName}&Password={Password}",
Method = "POST")]
string ValidateUser(string Username, string Password);
}
Class Demo :
public class Demo:IDemo
{
public string ValidateUser(string Username, string Password)
{
Users objUser = new Users();
objUser.UserID = Username;
objUser.Password = Password;
string Msg = LoginDataService.ValidateUser(Username, Password);
return Msg;
}
}
localhost:49922/Demo.svc/ValidateUser?Username=demo&Password=demo (with http:\)
When I try to parse the above URL under the Post Method in Fiddler2 I got Bad Request HTTP400 error.
Can anyone help me what is wrong in my code.
Thanks & Regards,
Vijay
Your URI template looks like you are sending the parameters in the URL. But when you use POST the parameters are sent in the http body.
Note you should not send the username and passord in the url as it can be logged.
For the above REST method the POST from Fiddler needs to be as shown below:
POST http://localhost/Sample/Sample.svc/ValidateUser?Username=demo&Password=demo HTTP/1.1
User-Agent: Fiddler
Content-Type: application/json
Host: rajeshwin7
Content-Length: 0
Doing so i get back a 200 OK HTTP Status as shown below:
HTTP/1.1 200 OK
Cache-Control: private
Content-Length: 44
Content-Type: application/json; charset=utf-8
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Thu, 14 Jun 2012 15:35:28 GMT
"Server returns username demo with password demo"
probably something i doing wrong, but i am returning XML from my WCF Rest service which is built with VS 2010. In fiddler you can see here that it returns test/html as the content-type
HTTP/1.1 200 OK
Cache-Control: private
Content-Length: 222
Content-Type: text/html; charset=utf-8
Server: Microsoft-IIS/7.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Mon, 16 Aug 2010 20:49:55 GMT
So i went ahead and added the following on the webget attribute on my method but it still returns text/html ... I presume that i should return the content type of text/xml because i am in fact returning XML?
Heres my method, i added the ResponseFormat to the attribute... I wasn't sure if i needed bodystyle (i have no idea what it does but saw it in an example :-) )
[WebGet(UriTemplate = "", BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Xml)]
public List<SampleItem> GetCollection()
{
// TODO: Replace the current implementation to return a collection of SampleItem instances
return new List<SampleItem>() { new SampleItem() { Id = 1, StringValue = "Hello" } };
}
anyway after the change and rebuilding of the project it still returns the wrong content type ... am i missign somthing?
HTTP/1.1 200 OK
Cache-Control: private
Content-Length: 222
Content-Type: text/html; charset=utf-8
Server: Microsoft-IIS/7.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Mon, 16 Aug 2010 20:54:15 GMT
EDIT
Ok i got a working solution but the attribute method has NO EFFECT, very strange...but if i put this
WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";
Now i check fiddler and the content-type is actually text/xml.
But i need to put this in every method and the attribute method seems to have no effect.
Anybody know why?
According to this the Firefox request headers has a higher priority for text/html than text/xml, resulting in WCF service methods decorated with xml or json returning with the "wrong" response, although I can imagine it is the correct behavior.
You can force a response content type by explicitly setting
WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";
or equivalent. I guess this is the only alternative if you truly want to force a specific content type response for all browsers/clients.
See e.g.
WCF ResponseFormat For WebGet
I think you want e.g.
OutgoingWebResponseContext context =
WebOperationContext.Current.OutgoingResponse;
context.ContentType = "image/jpeg";
ResponseFormat controls something else.
Old post, but here is what I found on MSDN's Blog Getting Started with WCF WebHttp Services in .NET 4:
Your project has to use the Full .NET 4 Framework, not the Client Profile.
Once I did that, and restarted the project, I was able to add System.ServiceModel.Web from the list of References.
I hope this helps someone.
I've been banging my head against the wall for the past couple of hours, here's what we're trying to do: a method expects a primitive/simple type as the request body. Originally we tried with a boolean, but that didn't work so we tried with string and object. Same thing.
Here's the server-side code
[OperationContract]
[WebInvoke(UriTemplate = "/foo/{foo_id}/bar", Method = "POST", ResponseFormat=WebMessageFormat.JSON)]
string G(string foo_id, string content);
And here's the request in Fiddler:
Header:
User-Agent: Fiddler
Host: localhost
Content-Type: 'application/json',
Content-Length: 19
Body:
"hello_world"
We tried to wrap "hello_world" in a json object, like {"content":"hello_world"} but no luck.
Any thoughts?
Works fine for me, here's my code:
[OperationContract]
[WebInvoke(UriTemplate = "/foo/{foo_id}/bar", Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
public string G(string foo_id, string content)
{
return content + foo_id;
}
You didn't set the request format (a pain I know :))
Here's my Fiddler request:
User-Agent: Fiddler
Content-Type: application/json
Host: localhost:54287
Content-Length: 7
"Hello"