System.InvalidOperationException: Request format is invalid: multipart/form-data; boundary Error When Calling .Net Web Service From PHP



TODO:

Have you ever tried to use php/curl to call a .Net Webservice and received the following:

System.InvalidOperationException: 

Request format is invalid: multipart/form-data;

boundary=----------------------------7d78134d9ec2.
 at System.Web.Services.Protocols.HttpServerProtocol.ReadParameters()
 at System.Web.Services.Protocols.WebServiceHandler.CoreProcessRequest()

 

SOLUTION:

 

<?php
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_HEADER, 0);
	curl_setopt($ch, CURLOPT_VERBOSE, 0);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)");
	curl_setopt($ch, CURLOPT_POST, true);
	curl_setopt($ch, CURLOPT_URL,'http://my.webservice.com/MyService.asmx/MyMethod' );
	$post_array = array(
			"Param1"=>'xyz',
			"Param2"=>'abc',
			"Param3"=>'123'
	);

	//url-ify the data
	foreach($post_array as $key=>$value) 
	{ 
		$post_array_string .= $key.'='.$value.'&'; 
	}
	$post_array_string = rtrim($post_array_string,'&');
	//set the url, number of POST vars, POST data
	curl_setopt($ch,CURLOPT_POST,count($post_array ));
	curl_setopt($ch,CURLOPT_POSTFIELDS,$post_array_string);
	$response = curl_exec($ch);
	print_r($response);
?>

 

NOTES:

This happens when you have parameters in your web method.  If you have no parameters, you can just access the Form["Param1"] to get to the data and do not need this foreach code at the end.

How To Call A .Net Web Service from cURL / PHP



TODO:

Have you ever wanted to post an image to a .Net Web Service using cURL and PHP?

 

SOLUTION:

 

<?php
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_HEADER, 0);
	curl_setopt($ch, CURLOPT_VERBOSE, 0);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)");
	curl_setopt($ch, CURLOPT_POST, true);
	curl_setopt($ch, CURLOPT_URL, 'http://my.service.com/MyService.asmx/MyMethod' );

	$post_array = array(
				"FileName"=>'test.jpg',
				"ImageData"=>'@C:/test.jpg',
				"Param1"=> 'data1',
				"Param2"=> 'data2'
	);

	curl_setopt($ch, CURLOPT_POSTFIELDS, $post_array); 
	$response = curl_exec($ch);
	print_r($response);
?>

NOTES:

.Net Web Service Method should be parameterless, and use the HttpContext and HttpFileCollection objects.