How do I call an ASHX from inside an ASPX.VB function?

前端 未结 2 715
灰色年华
灰色年华 2021-01-24 07:47

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\

相关标签:
2条回答
  • 2021-01-24 07:54

    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.

    0 讨论(0)
  • 2021-01-24 07:56

    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

    0 讨论(0)
提交回复
热议问题