Posting an image and textual based data to a wcf service
I have a requirement to write a web service that allows me to post an image to a server along with some additional information about that image.
I'm completely new to developing web services (normally clien开发者_开发技巧t side dev) so I'm a little stumped as to what I need to look into and try.
How do you post binary data and plain text into a servic?
What RequestFormat
should I use?
Bit of a waffly question but I just need some direction rather than a solution as I can't seem to find much online.
After reading this guide to building restuful services I figured I was going about the problem the wrong way. The image and text are actually two seperate resources and so should probably be handled seperately. I now have a service that uploads an image and returns a uri to that image and a seperate service to post textual data relating to that image along with the uri to that image.
Though I don't have experience with WCF, I can tell you a painless way to handle POSTing/PUTting of binary data in a REST API (especially one with a mix of text + binary) is to encode the binary data as base64 and treat it much like any other text data in your API.
Yes, there is a slight overhead with base64 in terms of size and an additional encode/decode process, however, base64 is typically only 1.37x larger than binary.
I find in many cases the overhead is well worth avoiding the pain that can be involved with binary data in APIs, especially when you need to POST/PUT a combination of binary and text data. If you wanted to POST an image and additional meta/text data you could easily do so with a json string ("image" would be your base64 encoded image)...
{
"image":"aGVsbG8...gd29ybGQ=",
"user" : 1234,
"sub_title": "A picture from my trip to Pittsburgh"
}
This is by no means the best solution for all cases, and as I said, I'm not a WCF expert, but it's certainly something to consider in the general case to make your life easier.
If you are using WebServiceHost in WCF 3.5 then you need to read this. If you have to use WCF to do HTTP based stuff then try and get onto .Net 4. I believe they have made a whole lot of things much easier.
If you are stuck with 3.5, welcome to a world of pain. Find everything you can written by Aaron Skonnard on the subject. And as I suggested in the comments of the other question, learn how to use SvcTrace.
精彩评论