I have a straitforward "helloWorld" webService example:
using System;
using System.Web;
using System.Web.Services;
namespace WebServiceTest
{
public class WebServiceTest : System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld(int number)
{
return "Hello World" + number;
}
}
}
How and where can I validate if the "number" is actually an int type If I write a string instead of a number the follwing exception is raise and everything blows up. I know that I need to make a validation before the method receives the arguments, but I do not know where. Could someone help me
System.ArgumentException: Cannot convert 256 to System.Byte.
Parameter name: type ---> System.OverflowException: Value was either too large or too small for an unsigned byte.
at System.Byte.Parse(String s, NumberStyles style, IFormatProvider provider)
at System.String.System.IConvertible.ToByte(IFormatProvider provider)
at System.Convert.ChangeType(Object value, Type conversionType, IFormatProvider provider)
at System.Convert.ChangeType(Object value, Type conversionType)
at System.Web.Services.Protocols.ScalarFormatter.FromString(String value, Type type)
--- End of inner exception stack trace ---
at System.Web.Services.Protocols.ScalarFormatter.FromString(String value, Type type)
at System.Web.Services.Protocols.ValueCollectionParameterReader.Read(NameValueCollection collection)
at System.Web.Services.Protocols.UrlParameterReader.Read(HttpRequest request)
at System.Web.Services.Protocols.HttpServerProtocol.ReadParameters()
at System.Web.Services.Protocols.WebServiceHandler.Invoke()
at System.Web.Services.Protocols.WebServiceHandler.CoreProcessRequest()

WebMethod argument validation
AnaC
Hi,
You have to declare the input parameter as string and then to convert it to int.
Use a try … catch construct for conversion. If the conversion fails, the variable is not an integer.
Example:
using System;
using System.Web;
using System.Web.Services;
namespace WebServiceTest
{
public class WebServiceTest : ystem.Web.Services.WebService
{
[WebMethod]
public string HelloWorld(string number)
{
try
{
Convert.ToInt32(number);
return "Hello world " + number;
}
catch
{
return "Invalid number";
}
}
}
}
Have a fun!
Valentin
Do not hesitate to contact me!
www.wwv-it.eu
valentin.welter@t-online.de
davidbellot
mPaskov
That is wrong!
Every Web Method has to check the input parameters. That was a very simply case, but what would happen in case of a calendar date input parameter
An exception failure is utmost unwanted and the Web Methods must avoid at all such failures.
Have a fun!
Valentin
MCP C#
Do not hesitate to contact me!
www.wwv-it.eu
valentin.welter@t-online.de