views:

1526

answers:

2

I need to get a value from an API I made with ASHX and normally it is called from javascript but I need to call it right in ASP.NET I figured this shouldn't be a problem but I'm not sure the syntax.

+2  A: 

Well you have a couple options

  1. You can refactor the code in your ASHX to be in a shared library so you can access the methods directly and so can the handler.
  2. You can instantiate the handler and invoke the members if they aren't private.
  3. You can create a webrequest to the handler and handle the response.

These are just a few of the easy ways.

I personally like the first method because it promotes code reuse, but depending on scenario you can do what you like.

Edit to provide answers for question in comment.

Essentially Yes... Instead of having a bunch of code in your handler you make a class called something meaningful to you contextually. Inside that class you place the logic that was in your handler. Then from your handler you can create an instance or call a static version of the class (depending on how you implemented it) passing it the HttpContext object or whatever is required for that logic to run correctly. Do the same thing in your ASPX page. You can now call into an object that contains the logic from anywhere in your app instead of having it reside in the handler alone.

EX:

Public Class MyCommonLogic
    Public Shared Function ReturnSomethingCommon(context As HttpContext) As String
        Return "Hello World!"
    End Function
End Class

Then from the handler or the aspx page..

Dim something As String = MyCommonLogic.ReturnSomethingCommon(...)

I made the function static, but that is just an example of course I would implement it however would make more sense in your scenario.

Changed code to VB sorry about that.

Quintin Robinson
I like idea 1 but I'm not sure what that means, I make a new class that has all the code and then in the ashx instead of having the code I just create a new instance of the class I made and pass the values to the functions of that object right?
shogun
I will elaborate in an edit.
Quintin Robinson
A: 

If the ASHX is on the same server especially if its within the same web app, you should refactor your logic out of the ashx into a common class that both the aspx and ashx can call.

Otherwise you can look at using: System.Net.WebClient

JoshBerke