【问题标题】:how do you pass an httpcontext object to a web service如何将 httpcontext 对象传递给 Web 服务
【发布时间】:2012-08-20 17:21:07
【问题描述】:

如何将 httpcontext.current 对象传递给 Web 服务并在服务中使用该对象,我收到一条错误消息,提示它需要一个字符串 - 很明显,这一定是可能的?

Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols

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

    <WebMethod()> _
    Public Sub doThis(ByVal HC As HttpContext)
        'do something
    End Sub
End Class


Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    Dim s As test2.WebService = New test2.WebService
    s.doThis(HttpContext.Current)
End Sub

【问题讨论】:

  • 这必须通过依赖注入来完成
  • 你有例子吗?谢谢

标签: asp.net vb.net web-services service


【解决方案1】:

HttpContext 不是可序列化的,因此不能作为字符串发送。 HttpContext 是一个具有其他复杂属性的复杂对象,所以如果你将它序列化它会相当大(这意味着发送数据会慢很多)。

我认为最好将您需要的信息封装在自定义类中并将其发送到服务。

即创建一个可以序列化的简单类型(字符串、整数、双精度等)的类,并用你需要的信息填充它。

【讨论】:

  • @Hello-World 我已经更新了答案,不太清楚你想让我解释什么=)
  • 封装的想法很好,尤其是当您只需要几个非常简单的属性时。但是假设你需要像HttpContext.Current.Request 这样更复杂的东西,你仍然会被卡住。只使用ByRef 有什么反感?
【解决方案2】:

您不能传递HttpContext ByValByVal 表示按值,这意味着需要复制HttpContext 的值才能传递给您的方法。由于它是一个 [复杂] 对象,因此您不能这样做。相反,您需要将其传递给 ByRef,这意味着将对对象的引用传递给您的方法并处理该引用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多