RESTfull Service is not accepting object as parameter - wcf

[WebInvoke(Method="POST",UriTemplate="/Users",RequestFormat=WebMessageFormat.Json)]
public string StudentUsers(Student user)
{
return string.Format("Hello {0}", user.Name);
}
Above code is my REST service. And my client code is :
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";
Student user =
new Stuent {
Name="Test User",
Email = "test#test.com",
Password = "test"
};
DataContractJsonSerializer ser = new DataContractJsonSerializer(user.GetType());
MemoryStream ms = new MemoryStream();
ser.WriteObject(ms, user);
String json = Encoding.UTF8.GetString(ms.ToArray());
StreamWriter writer = new StreamWriter(request.GetRequestStream());
writer.Write(json);
writer.Close();
var httpResponse = (HttpWebResponse)request.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
Console.WriteLine(result);
}
My service is hosted and I'm using webHttpBinding. When I debug my REST service I'm receiving null in Student object. I am sure that my post method is sending data as I test it by taking Name, Email and Password as parameters at REST service so my data is posted successfully but the thing is my Json data which is posted is not getting converted to Student object. I read somewhere that RESTfull Service will convert that Json data to object. Is that true or we need to convert it explicitly?

You need to sent the Content-Length for your POST-ed data:
request.ContentLength = ms.Length;
see here for more details:

I have fixed the issue by changing WebInvoke to
[WebInvoke(Method="POST",UriTemplate="/Users",RequestFormat=WebMessageFormat.Json,BodyStyle = WebMessageBodyStyle.Bare)]

Related

Attaching files to Azure DevOps work item

I am trying to attach files (screenshots) to an Azure DevOps work item via a C# desktop app. I have managed to attach files, but they're not valid image files, which leads me to believe that I'm doing something wrong in uploading them.
From the documentation DevOps Create Attachment below is the section on the Request body of the API call, which is rather vague.
From a GitHub discussion this answer seems to suggest that I just upload the binary content directly, which is what I'm doing.
My code is as follows
var img = File.ReadAllBytes(fname);
string query = #"/_apis/wit/attachments?fileName=" + fname + #"&api-version=6.0"
string response = AzureUtils.AttachFile(query, img, "POST", false, "application/octet-stream");
Is it correct that I literally pass in the byte array which is read from the file (variable img) as the body?
Why is it not a valid file when I look at it in DevOps?
The code for AttachFile is
public static string AttachFile(string query, byte[] data = null, string method = "GET",
bool dontUseBaseURL = false, string contentType = "application/json-patch+json")
{
try
{
HttpWebRequest request = WebRequest.Create(query) as HttpWebRequest;
request.ContentType = contentType;
request.Method = method;
request.Proxy.Credentials = CredentialCache.DefaultCredentials;
request.Headers.Add("Authorization", "Basic " +
Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{1}", ["AzurePAT"]))));
if (data != null)
{
using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(data);
}
}
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
string result = string.Empty;
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
result = reader.ReadToEnd();
}
request = null;
response = null;
return result;
}

Post a string to restful webservice in C#

I am provided a webservice url similar to:
http://ericdev35:7280/persons/persons/
and a username and password.
I want to make a post call on this web service from WPF application.
The data to be sent to the service is the first name and last name of a person in the format:
"fname=Abc&lname=Xyz"
How can I make a call for this in C#?
Here is the code that I have tried:
HttpWebRequest httpWebRequest = (HttpWebRequest) WebRequest.Create("http://ericdev35:7280/persons/persons/");
httpWebRequest.Method = "POST";
httpWebRequest.ContentType = "application/json";
httpWebRequest.Credentials = new NetworkCredential(username, password);
string data = "fname=Abc&lname=Xyz";
StreamWriter writer = new StreamWriter(httpWebRequest.GetRequestStream());
writer.Write(data);
writer.Close();
This does not give me any error but I cannot see the data that I have posted. Is there anything that needs to be corrected?
Is the Content Type correct?
This Method posts json.
After that it gets the response and deserialize the Json Object.
private static string PostJson<T1>(string p_url, string p_json, string p_method, out T1 p_target)
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create(p_url);
httpWebRequest.UseDefaultCredentials = true;
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = p_method;
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(p_json);
streamWriter.Flush();
streamWriter.Close();
}
HttpWebResponse httpResponse;
try
{
httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
}
catch (WebException ex)
{
httpResponse = ex.Response as HttpWebResponse;
}
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var a_result = streamReader.ReadToEnd();
//If you dont need a Json object delete anything behind here
try
{
p_target = JsonConvert.DeserializeObject<T1>(a_result);
}
catch { p_target = default(T1); }
return a_result;
}
}

Restful WCF bad request error

I have a simple resftul wcf service. The .svc file looks like this
<%# ServiceHost Service="NameSpace.RestfulService" Factory="System.ServiceModel.Activation.WebServiceHostFactory" %>
The interface method declaration
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "test2", RequestFormat = WebMessageFormat.Json,ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
List<MyObj> Test2(MyObj test);
Method implementation
public List<MyObj> Test2(MyObj test)
{
return new List<MyObj>() { new MyObj() { MyObjId = "1", RowVersion = 1 }, new MyObj() { MyObj= "2", RowVersion = 2 } };
}
Method on a wpf client to call the service
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(MyObj));
MemoryStream ms = new MemoryStream();
serializer.WriteObject(ms, new MyObj() { MyObjId = "A", RowVersion = 1 });
string jason = Encoding.Default.GetString(ms.ToArray());
//get a handle to the request stream to write data to it
WebRequest myRequest = WebRequest.Create("http://localhost/MyService.svc/test2");
myRequest.Method = "POST";
myRequest.ContentType = "application/jason; charset=utf-8";
StreamWriter sw = new StreamWriter(myRequest.GetRequestStream());
sw.Write(jason);
sw.Close();
//get a handle to the response stream from the server to read the response
WebResponse myResponse = myRequest.GetResponse();
DataContractJsonSerializer RecData = new DataContractJsonSerializer(typeof(List<MyObj>));
var result = (List<MyObj>)RecData.ReadObject(myResponse.GetResponseStream());
When I try to get the RequestStream "myRequest.GetRequestStream()" it says bad request error 400.
Any idea what might be causing this error?
Thanks
Your content type is "application/jason; charset=utf-8". JSON's MIME-type is "application/json" (no 'a'). This is my likely why it 400's when you send the initial headers (which is done when you call GetRequestStream) because the WCF service doesn't recognize the content-type and immediately rejects the request.

Passing object with WCF RESTful

[WebInvoke(Method = "PUT", UriTemplate = "users/{username}")]
[OperationContract]
void PutUser(string username, User newValue);//update a user
I have a update user method defined as showed above. Then I use a HttpWebRequest to test the method, but how can I pass the User object with this HttpWebResquest?
The following code is what I got so far.
string uri = "http://localhost:8080/userservice/users/userA";
HttpWebRequest req = WebRequest.Create(uri) as HttpWebRequest;
req.Method = "PUT";
req.ContentType = " application/xml";
req.Proxy = null;
string uri = "http://localhost:8080/userservice/users/userA";
string user = "<User xmlns=\"http://schemas.datacontract.org/2004/07/RESTful\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\"><DOB>2009-01-18T00:00:00</DOB><Email>userA#example.com</Email><Id>1</Id><Name>Sample User</Name><Username>userA</Username></User>";
byte[] reqData = Encoding.UTF8.GetBytes(user);
HttpWebRequest req = WebRequest.Create(uri) as HttpWebRequest;
req.Method = "POST";
req.ContentType = " application/xml";
req.ContentLength = user.Length;
req.Proxy = null;
Stream reqStream = req.GetRequestStream();
reqStream.Write(reqData, 0, reqData.Length);
HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
string code = resp.StatusCode.ToString();
//StreamReader sr = new StreamReader( resp.GetResponseStream());
//string respStr = sr.ReadToEnd();
Console.WriteLine(code);
Console.Read();
I found the solution, I need to construct the xml string I want to pass and then write it into stream
In WCF/REST you don't pass an object, you pass a message.
If I were doing this, as a first step, I would create a WCF client that interacts with the service. I would examine the messages passed on the wire by the WCF client, and then I'd replicate that message with the HttpWebRequest.

WCF Post / WebRequest Works - WebClient doesn't

I have a WCF Service declared as follows:
[OperationContract, XmlSerializerFormat]
[WebInvoke(UriTemplate = "ProessUpload",
BodyStyle = WebMessageBodyStyle.Bare,
RequestFormat = WebMessageFormat.Xml)]
void ProcessUpload(ProductConfig stream);
I am trying to call this service using WebClient but I am always getting a response 400 (BadRequest) from the server. However if I use HttpWebRequest the WCF consumes my post and correctly responds with 200. I am also able to successfully construct a request using Fiddler to call the WCF Service.
WebClient Code
WebClient webClient = new WebClient();
webClient.Headers.Add("Content-Type", "application/xml");//; charset=utf-8
try
{
string result = webClient.UploadString("http://jeff-laptop/SalesAssist.ImageService/Process", "POST", data2);
}
catch (Exception ex)
{
var e = ex.InnerException;
}
HttpWebRequest code
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://jeff-laptop/SalesAssist.ImageService/Process");
request.ContentType = "application/xml";
request.Method = "POST";
request.KeepAlive = true;
using (Stream requestStream = request.GetRequestStream())
{
var bytes = Encoding.UTF8.GetBytes(data2);
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Close();
}
var response = (HttpWebResponse)request.GetResponse();
var abc = new StreamReader(response.GetResponseStream()).ReadToEnd();
The XML that is being sent
var data2 = #"<Product><Sku>3327</Sku><NameProduct</Name><Category>Bumper</Category><Brand Id='3'><Collection>14</Collection></Brand></Product>";
Why is that HttpWebRequest works and WebClient doesn't? I can't see a real difference in the sent headers via Fiddler.
Try setting the Encoding property on the WebClient before you send the string. Since you aren't specifying it I suspect it defaults to ASCII. Quoting from the UploadString reference page.
Before uploading the string, this
method converts it to a Byte array
using the encoding specified in the
Encoding property. This method blocks
while the string is transmitted. To
send a string and continue executing
while waiting for the server's
response, use one of the
UploadStringAsync methods.
webClient.Encoding = Encoding.UTF8;