mbeasley
mbeasley

Reputation: 4874

Call ASP.NET pagemethod from external script

Background

I have an ASP.NET site, hosted internally on our company's intranet server. The site uses the client's default network credentials for authentication. The main page for the site, Default.aspx contains the following web method that syncs some data from an Oracle server to an MS SQL server:

<WebMethod()> _
Public Shared Sub syncOracle()        
    OracleSync.MainSync()
End Sub

When I access that webmethod from site itself (say from a button on the page or something) it works fine and performs as expected.

Problem

I would like to setup a scheduled task on the server that calls this method on a period basis. My approach so far has been to write a simple console script in VB that would access the web method via an HTTPWebRequest:

Sub Main()
    Dim myReq As HttpWebRequest = _
       WebRequest.Create("http://vm-prod1/dev/default.aspx/syncOracle")
    myReq.Credentials = CredentialCache.DefaultNetworkCredentials
    myReq.Method = "POST"
    myReq.ContentLength = 0

    Dim response As HttpWebResponse = CType(myReq.GetResponse(), HttpWebResponse)

    Console.WriteLine(response.StatusCode)

    Console.ReadKey()
End Sub

This returns an "OK" status of 200, but when I parse the actual response, I'm not getting the response that I get when I access the method from the page (instead, I get the code for the entire aspx page). And the sync is not firing.

Question

Does anyone have any insight into either a better / different approach (maybe not using HttpWebRequests) or modification to my current approach that may work better? Thank you in advance!

Upvotes: 2

Views: 619

Answers (1)

ChrisLively
ChrisLively

Reputation: 88072

By far the easiest thing you could do is drop page methods and switch to using a simple Generic Handler.

With a generic handler you don't have all of the standard web forms page lifecycle and instead it gives you an extremely flexible and easy way to run processing like you've described.

So, I'd add a generic handler (.ashx) file to the project. Put the code in you need to run. Then simply execute the page from console script.

Upvotes: 1

Related Questions