Search code examples
c#asp.netwebmethod

How to define an if statement in WebMethod in C#


I'm trying to define an if statement in one of WebMethods on my website page in order to check if the value of the University Offer field is null, if the value is null then the method executes as expected. If the value isn't null then I want it to return a error message.

Trouble is I seem to be hitting two problems.

  1. What do I put in the else condition to indicate there was an error in saving this value to this field? I tried return but my method has a return type of void which makes return processes tricky to implement.

  2. When I execute my code and test it on my server, trying to access that specific method comes back with a message indicating "The test form is only available for requests from the local machine.

Here is the code for that method that I was able to define so far.

[WebMethod]
public void EditNAA_ApplicationOffer(NAA_Applications App, int ApplicationId, string UniversityOffer)
{

    NAA_Applications _EditAO = _NAAService.Get_Applicant_Application(ApplicationId);

    if (_EditAO.UniversityOffer == null)
    {
        _NAAService.EditNAA_ApplicationOffer(ApplicationId, UniversityOffer);
    }
    else
    {

    }


}

Can anyone help me with these two issues?


Solution

    1. What do I put in the else condition to indicate there was an error in saving this value to this field?

    You could indicate an error happened in web method by throwing SoapException:

    if (_EditAO.UniversityOffer == null)
    {
        _NAAService.EditNAA_ApplicationOffer(ApplicationId, UniversityOffer);
    }
    else
    {
        throw new SoapException("Some error has occurred", SoapException.ClientFaultCode);
    }
    

    In this case on the client you will get HTTP Error 500 with provided error message.

    1. When I execute my code and test it on my server, trying to access that specific method comes back with a message indicating "The test form is only available for requests from the local machine.

    Default settings does not allow invoking service via test form from remote hosts. If you are OK with allowing anyone to play with your service, you should add following <webServices> section to your web.config (taken from this answer):

    <configuration>
        <system.web>
         <webServices>
            <protocols>
                <add name="HttpGet"/>
                <add name="HttpPost"/>
            </protocols>
        </webServices>
        </system.web>
    </configuration>