【问题标题】:Response.Write JSONP using JQuery and WCFResponse.Write JSONP 使用 JQuery 和 WCF
【发布时间】:2023-03-24 02:53:01
【问题描述】:

更新:

无法激活该服务,因为它不支持 ASP.NET 兼容性。为此应用程序启用了 ASP.NET 兼容性。在 web.config 中关闭 ASP.NET 兼容模式,或将 AspNetCompatibilityRequirements 属性添加到服务类型,并将 RequirementsMode 设置为“Allowed”或“Required”。

当我尝试访问 wcf 服务时出现此错误:原因是 HttpContext.Current 为空,在这种情况下我该怎么办?有什么帮助吗?

对象引用未设置为对象的实例。

 System.Web.Script.Serialization.JavaScriptSerializer s = new            System.Web.Script.Serialization.JavaScriptSerializer();
        Person p = new Person() { FirstName = "First name", LastName= "last name" };
        string json = s.Serialize(p);
        System.Web.HttpContext.Current.Response.Write("jsoncallback" + json);} //error

【问题讨论】:

  • 您确定以声明方式添加了它。该错误非常明确。看起来您试图在没有为该服务启用 ASP.Net 兼容模式的情况下访问您的服务。
  • 我做了,我仔细检查了......
  • 好吧...几个问题。 1.) 您的 WCF 服务是否托管在 IIS 中? 2.) 您是否将声明放在您的服务实现或合同上?
  • 不知道出了什么问题,但它现在可以工作,托管在 IIS 中

标签: asp.net wcf jsonp


【解决方案1】:

HttpContext 是一个 ASP.Net 结构。如果您希望能够在您的服务中访问它,那么您需要为您的服务启用ASP.Net Compatibility

通过 web.config:

<system.serviceModel>
        <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />  
</system.serviceModel>

或声明式:

[AspNetCompatibilityRequirements(RequirementsMode=AspNetCompatibilityRequirementsMode.Required)]  
public class MyService : IMyService { ... }

【讨论】:

  • 我尝试通过 web.config 和 delcaratively 添加,但我收到此错误:我更新了我的问题。
  • 您必须在 web.config 和服务中执行此操作。如果他们不匹配错误。
【解决方案2】:

如果简单的响应写入适合您,那么考虑使用简单的 HttpHandler(通过实现 IHttpHandler 接口)。 Response 对象并不意味着在 WCF 服务中使用...

如果 WCF 适合您(也许它提供的技术堆栈是您需要的东西),那么请考虑使用已经存在的管道来输出 json:

[ServiceContract] 
public interface IService
{
    [OperationContract]
    [WebGet(ResponseFormat = WebMessageFormat.**Json**)]
    String DoStuff();

}

【讨论】:

  • Rune:我正在跨域工作,这就是为什么我试图简单地流式传输数据......
  • 简单的 HttpHandler 和 WCF 方法都涵盖了跨域场景。事实上,唯一没有(没有一些调整)的是 RIA 服务和 MVC JsonResult。
猜你喜欢
  • 2011-04-15
  • 1970-01-01
  • 2013-01-11
  • 2013-10-23
  • 2012-02-19
  • 2012-04-10
  • 2011-01-22
  • 2011-12-10
  • 2012-11-01
相关资源
最近更新 更多