• 0

[C#] Am I missing a pitfall with base64 encode sending?


Question

I am always learning different parts of the C# language b/c lets face it, it's a lot of fun :). I've decided to configure my wcf service as a rest service which supports json request/response instead of xml. All has gone well and I can serialize/deserialize my messages into complex classes so far, unless I send a bunch of data in them. I've tried to change my readerQuotas, etc, etc but everytime I try to make a call it says "Error: Bad Data". I know the service works because I can call simple functions and pass data to/from the service. But if I pass a class with 3 byte[] properties each 128 bytes in length it fails. If I pass the same class with each byte[] param with 3 bytes of data it goes through (I base64 encode each complex class after serializing them). Here is my example code:

This example passes and goes through:

GetTestSalesRequest req = new GetTestSalesRequest()
			{
				CurrentTest = new byte[] { 1 },
				CurrentMTest = new byte[] { 4 },
				UserName = this.gl_userName,// <---- is a string
				UserPwd = new byte[] { 2 }
			};

string test = await this.gl_client2.TestFunc(req);
			System.Diagnostics.Debug.WriteLine("Test function: {0}", test);

This example fails.


GetTestSalesRequest req = new GetTestSalesRequest()
			{
				CurrentTest = CryptographicEngine.Encrypt(keySvr, Encoding.UTF8.GetBytes(test1.ToString()).AsBuffer(), null).ToArray(), // <---- is a byte[]
				CurrentMTest = CryptographicEngine.Encrypt(keySvr, Encoding.UTF8.GetBytes(test2.ToString()).AsBuffer(), null).ToArray(), //<---- is a  byte[]
				UserName = this.gl_userName,// <---- is a string
				UserPwd = this.gl_userPwd // <--- is a byte[]
			};

string test = await this.gl_client2.TestFunc(req);
			System.Diagnostics.Debug.WriteLine("Test function: {0}", test);


public async Task<string> TestFunc(GetTestSalesRequest request)
		{

string resBody = null;
			byte[] testStr = Encoding.UTF8.GetBytes(WebHelperClass.SerializeJSONObj<GetTestSalesRequest>(request));
			string addr = string.Format("{0}/TestFunc/{1}", this.gl_baseAddr, Convert.ToBase64String(testStr));
			WebRequest req = WebRequest.Create(addr);
			HttpWebResponse res = await req.GetResponseAsync() as HttpWebResponse;
			if (res.StatusCode == HttpStatusCode.OK)
			{
				using (Stream stream = res.GetResponseStream())
				{
					using (StreamReader sr = new StreamReader(stream))
					{
						resBody = sr.ReadToEnd();
						sr.Dispose();
					}
				}
			}
			return resBody;
}

Is there a pitfall I'm going into here? What am I missing that is really obvious because this has to be possible to be done.

10 answers to this question

Recommended Posts

  • 0

Not really strong with debugging other peoples code.. But.. have you tried:

1) Sending the same data but un-encrypted

2) Using AsciiEncoding.Ascii instead of Encoding.UTF8 for the base64 encode?

3) It looks like you are just using the CryptographicEngine, that won't base64 it, have you tried just a plain-jane base64 encode?

4) You pass in a few variables, are you sure they are all initialized correctly?

  • 0

Well basically I'm just taking the json string (that was created by serializing the complex class) in TestFunc and base64 encoding it to send it across to the rest service so I don't have a long query string similar to /TestFunc/{[80,10,01,01,30,10,10], "test":"etc"}. So I am base64 encoding the whole thing then decoding it on the rest service side. If I send the class with only have small amounts of byte data it goes through just fine. If I send each byte[] with having 128 different indexes each then it fails. Ingramator which files do you want? The debugger just outputs saying "The remote server returned an error: (400) Bad Request."

System.Net.WebException was unhandled by user code

HResult=-2146233079

Message=The remote server returned an error: (400) Bad Request.

Source=System

StackTrace:

at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)

at System.Threading.Tasks.TaskFactory`1.FromAsyncCoreLogic(IAsyncResult iar, Func`2 endFunction, Action`1 endAction, Task`1 promise, Boolean requiresSynchronization)

--- End of stack trace from previous location where exception was thrown ---

at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)

at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()

at TestSaleStoreApp.TestSaleRestSvcClient.<TestFunc>d__a.MoveNext() in c:\Users\User\Documents\Visual Studio 2012\Projects\TestSaleStoreApp\TestSaleStoreApp\TestSaleRestSvcClient.cs:line 50

--- End of stack trace from previous location where exception was thrown ---

at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)

at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()

at TestSaleStoreApp.MainUserPg.<initSettings>d__16.MoveNext() in c:\Users\User\Documents\Visual Studio 2012\Projects\TestSaleStoreApp\TestSaleStoreApp\MainUserPg.xaml.cs:line 524

InnerException:

If you need more info let me know :) I'm stumped on this one. As for the ASCII I haven't tried that yet I'll look into it later today but I'm suspecting it has to do with the length of the content (which I've changed the readerQuota settings).

I also really appreciate the help so far guys!

  • 0

It's quite possible you're just sending too much data via the query string, why aren't you just sending it as the request body instead?

base64 makes the content larger, and you don't need to do it with text (like JSON).

  • 0

@The_Decryptor b/c I'm new to using Rest services I'm used to using SOAP :) I'll look into that thanks.

EDIT: My url looks like this:

localhost:8733/Design_Time_Addresses/TestSaleRestSvc/Service1/TestFunc/eyJDdXJyZW50Q29vcmRzTGF0IjpbMiwzLDRdLCJDdXJyZW50Q29vcmRzTG9uZyI6WzMsNCw1XSwiVXNlck5hbWUiOiJyeWFuIiwiVXNlclB3ZCI6WzFdfQ==&pwdKey=Aw==&latKey=JbU2hfwNBi1vHZxH5OnUcKabsT1kx16jqn3BAxLDXPTCHbyIlDyPOoK0NNQVSLmaOD5x1bjzipTM9VJOaQgTIgjmqNtX+l9Jq2EeetSQI58RhCwUFRQGOpKaLEJ03JeZ5UjD3rTzm2HFr5P0SvQBYBsgLB9W1je3PPoD28Ro7IU=&longKey=AQ=="]localhost:8733/Design_Time_Addresses/TestSaleRestSvc/Service1/TestFunc/eyJDdXJyZW50Q29vcmRzTGF0IjpbMiwzLDRdLCJDdXJyZW50Q29vcmRzTG9uZyI6WzMsNCw1XSwiVXNlck5hbWUiOiJyeWFuIiwiVXNlclB3ZCI6WzFdfQ==&pwdKey=Aw==&latKey=JbU2hfwNBi1vHZxH5OnUcKabsT1kx16jqn3BAxLDXPTCHbyIlDyPOoK0NNQVSLmaOD5x1bjzipTM9VJOaQgTIgjmqNtX+l9Jq2EeetSQI58RhCwUFRQGOpKaLEJ03JeZ5UjD3rTzm2HFr5P0SvQBYBsgLB9W1je3PPoD28Ro7IU=&longKey=AQ==

  • 0

Hmm it's always to debug without having it in front of you but I can try and point you in the right direction! :) If its working with smaller data samples it may be that you're [trying to encode an unsupported data type]/[base64 doesn't know what to encode so its sending invalid data] but I can't tell from the log there. The most common problem I find is that the data buffer is not being completely filled or filled correctly so I'd investigate that first! Enable tracing first, instructions here http://msdn.microsoft.com/en-us/library/ms733025.aspx :p then test and it will show you exactly where the problem is occurring. Hope this helps, good luck with the project mate!

  • 0

So I want to take this time to thank everyone who helped me. You guys are all great assets to this community and I hope I can give back one day by finding other questions I can answer in this forum and post my 2 cents on the subject (you guys are just too quick it seems most of the time and say what I would say :) ). +1 to you all and I hope you have a good holiday.

This topic is now closed to further replies.
  • Posts

    • Who is paying for this 30x scale-up? Its sounds expensive.
    • Millions of users to benefit from Windows 11's new performance boost on Adobe Photoshop by Sayan Sen Despite the advent of AI-generated imagery, Adobe's Photoshop remains one of the most popular tools on this planet. Adobe does not have a publicly reported total user count but it's probably not wrong to assume there are millions. As of 2025, Adobe Creative Cloud has had approximately 41 million paid subscribers, many of whom likely use Photoshop. In addition, more than 166,000 companies worldwide are apparently also using the app. These figures are according to a very recent report by SQ Magazine. Out of them, it is fair to assume that many are probably running Windows. As such, there is good news for these users as Microsoft has announced Photoshop is getting a big 20% performance boost on x86-64 (AMD64) systems and a 13% bump-up on Arm devices. This is definitely great news for them as many have complained about the slow performance and general sluggishness of Photoshop on Windows 11 ever since the advent of the latter back in 2021. If you are wondering how Microsoft managed to do this, the answer lies in a combination of compiler-level optimizations and a technology called Sample Profile Guided Optimization (SPGO). According to Microsoft, Adobe worked closely with the company’s Visual C++ team and adopted the latest MSVC toolchain enhancements together with SPGO to squeeze more performance out of Photoshop’s CPU-bound workloads. Unlike traditional Profile Guided Optimization (PGO), which requires developers to create special instrumented builds and run lengthy training workloads, SPGO gathers performance data directly from optimized release binaries. This means Adobe could collect real-world usage information which gives a major advantage to this technique, as companies could leverage data collected from actual customer workloads rather than only relying on synthetic benchmark runs. In theory, this should allow optimizations to better reflect how users interact with software in the real world. Thanks to this, there are improvements to code layout, function inlining, hot-and-cold code separation, and other low-level tweaks that help processors execute instructions more efficiently. Essentially the compiler is better able to identify “hot” code paths, those which are most frequently executed, and optimize them accordingly.
    • "The 2TB Samsung 990 PRO NVMe SSD hits lowest price in over three months¨ I'd prefer to see the lowest price in over a year
    • Glad these prices are starting to come down, but that is still crazy. I bought the 2TB 9100 Pro (slightly more expensive version with PCIe 5.0) last year for $240.
    • The 2TB Samsung 990 PRO NVMe SSD hits lowest price in over three months by Sayan Sen Yesterday, we covered a really good deal wherein you can get a 4TB TeamGroup T-FORCE G50 NVMe PCIe Gen4 SSD for a low price of just $400 with a special discount coupon. That's just $100 per TB, making it a very good offer during these hard times. The deal is still live, so you can check it out in its dedicated article here if you do not want to miss out. Meanwhile, if you don't have that kind of budget but still wish to buy an SSD for a good price, the 2TB variant of the TeamGroup SSD at $280 its lowest price in over three months. Meanwhile, those seeking 2TB but faster performance can check out Samsung's 990 PRO, which has hit the lowest price also in the last quarter or so, as it's on sale for $370 (purchase links under the specs table down below). Thus, you want a faster drive, get the 990 Pro, or you want more capacity, grab the TeamGroup 4TB linked in the first para. The 990 PRO is a PCIe Gen4 NVMe SSD and still one of the fastest drives available today for under $500. Speaking of fast, sequential reads and writes are rated at 7450 MB/s and 6900 MB/s, respectively. The random throughputs for reads and writes are 1400K IOPS and 1550K IOPS, respectively. The 990 PRO is based on Samsung's 7th Gen V-NAND flash, and it too is TLC. It packs 2 gigs of LPDDR4 DRAM cache, which helps the random performance. The endurance rating for this is 1200 TBW (terabytes written), which should be sufficient for most users. The Samsung 990 PRO is compatible with the PlayStation 5, but if you are going to use the 990 PRO on a PC, check out the Samsung Magician app that lets you track your drive's health, update its firmware, customize various settings, and more. The tech specs are given below: Specification TeamGroup T-FORCE G50 2TB Samsung 990 PRO 2TB Interface PCIe 4.0 x4, NVMe 1.4 PCIe Gen 4.0 x4, NVMe 2.0 Form Factor M.2 2280 M.2 2280 Controller InnoGrit Controller Samsung In-house Controller NAND Flash 3D TLC 3D TLC DRAM Cache None (HMB supported) 2GB LPDDR4 Sequential Read (Max) 5,000 MB/s 7,450 MB/s Sequential Write (Max) 4,500 MB/s 6,900 MB/s Random Read (4K) Up to 600,000 IOPS Up to 1,400,000 IOPS Random Write (4K) Up to 700,000 IOPS Up to 1,550,000 IOPS TBW (Endurance) 1,300 TBW 1,200 TBW MTBF 3,000,000 hours 1,500,000 hours Operating Temperature 0°C to 70°C 0°C to 70°C Storage Temperature -40°C to 85°C -40°C to 85°C Shock Resistance 1,500G / 0.5ms 1,500G / 0.5ms Heatsink Patented Graphene Heat Spreader No Get them at the links below: Samsung 990 PRO SSD 2TB (MZ-V9P2T0B/AM): $369.99 (Sold and Shipped by Amazon US) TEAMGROUP T-Force G50 2TB SSD (TM8FFE002T0C129): $279.99 (Sold by TeamGroup, Shipped by Amazon US) Good to know This Amazon deal is U.S. specific, and not available in other regions unless specified. We only use first-party seller links (at the time of article publishing); ensure that you purchase from a first-party seller link only. Check out Today's Deals on Amazon | or our recent tech deals. Become a Prime member (for Students or SNAP) via Neowin Get Prime Access - Prime for half price (for qualifying Medicaid, EBT, SNAP) Subscribe to Prime Video, Audible Plus, Music Unlimited or Kindle Unlimited via Neowin As an Amazon Associate, we earn from qualifying purchases.
  • Recent Achievements

    • First Post
      Jocimo earned a badge
      First Post
    • Week One Done
      suprememobiles48 earned a badge
      Week One Done
    • One Month Later
      Windows Guy earned a badge
      One Month Later
    • One Month Later
      Prasann earned a badge
      One Month Later
    • Week One Done
      Prasann earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      519
    2. 2
      +Edouard
      174
    3. 3
      PsYcHoKiLLa
      90
    4. 4
      Steven P.
      81
    5. 5
      ATLien_0
      70
  • Tell a friend

    Love Neowin? Tell a friend!