Firstly I must apologise if my terminology is off. This is the first time I've explored .asmx
so I've probably gotten some things wrong. I'm mentioning this because I want you to correct me as it is an invaluable learning experience and I need to get it right.
I'm writing an Ajax enabled .asmx
web service to allow two browser based systems to talk to each other. In order for this to work I must initially authenticate with one of the systems to get the URL to use for all subsequent API calls to that same system. I only want to do this one time when the service is started and then remember this across all calls to all webmethods.
- How do I run a method only one time when the service is loaded by IIS?
- How do I store the result globally so that it can be accessed by every call to my webmethods?
I've seen two posts that touch on this ( 1 | 2 ) but neither made enough sense to help me.
I think I need to add a Global.asax
file and store the details in there, but I'm not sure if this is right and I still don't know how to run the method only once. Can I just override Application_Start
in here? This is what I would do on an ASPX page but I don't know how similar these two technologies are.
I've seen recommendations to use the constructor to run the method but it's my understanding that this may be called more than once so would be incorrect for my scenario.
For clarity my project currently only has two files, handler.asmx and handler.cs.
Handler.asmx
<%@ WebService Language="C#" CodeBehind="~/App_Code/handler.cs" Class="Handler" %>
Handler.cs
[WebService(Namespace = "http://localhost/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class Handler : WebService {
public Handler () {
// empty
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetSomeInformation() {
// does some stuff and then returns a string
}
}
This is what the Global.asax looked like after I added it:
Global.asax
<%@ Application Language="C#" %>
<script runat="server">
void Application_Start(object sender, EventArgs e)
{
}
void Application_End(object sender, EventArgs e)
{
}
// and all the other methods here like error, session start/end etc