Asp.Net Web Service - How to declare Public Variable

← PrevNext →

You can declare a Public variable in an Asp.Net web serivce by defining the variable "within" a class but outside the methods (web methods).

Web Service (C#)

using System;
using System.Web;
using System.Web.Services;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService {

    // declare public variable.
    public static int sResult = 0;

    // Calculate the percentage.
    [WebMethod()]
    public double percentage(double leftOperand, double rightOperand)
    {
        var perc = (leftOperand / rightOperand) * 100;
        sResult = Math.Round(perc);
        return sResult;
    }
}

Web Service (VB)

Imports System.Web
Imports System.Web.Services

<System.Web.Script.Services.ScriptService()> _
<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class WebService
    Inherits System.Web.Services.WebService

    // declare public variable.
    Public Shared sResult As Integer = 0

    ' Calculate the percentage.
    <WebMethod()> _
    Public Function percentage(ByVal leftOperand As Double, ByVal rightOperand As Double) As Double
        Dim perc = (leftOperand / rightOperand) * 100
        sResult = Math.Round(perc)

        Return sResult
    End Function
End Class

Access Public Variable from Code Behind

If you have declared public variables in your web service, then you should also know how to access the public variables from code behind.

Code behind (C#)

Assuming, there are two public variables in the web service.

public class WebService : System.Web.Services.WebService {
    // public variables.
    public static int sResult = 0;
    public static string sMessage = "";

    [WebMethod()]
    public double percentage()
    {
        ...
    }
}

You can access the public variables from the code behind by directly reference the variables using the class name.

protected void form1_Load(object sender, System.EventArgs e)
{
    var result = WebService.sResult;
    var msg = WebService.sMessage;
}

Code behind (VB)

Protected Sub form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles form1.Load
    Dim result = WebService.sResult
    Dim msg = WebService.sMessage
End Sub

access web service public variables from code behind in asp.net

← PreviousNext →