ASP.NET JQuery AJAX POST返回数据但在401响应中

问题描述:

我的应用程序中有一个Web页面,需要调用我设置为返回对象列表的Web服务。该呼叫建立像这样ASP.NET JQuery AJAX POST返回数据但在401响应中

$(document).ready(function() { 
    var response = $.ajax({ 
     type: 'POST', 
     contentType: 'application/json; charset=utf-8', 
     url: '/Ajax/service.asmx/GetObjects' 
    }); 

    response.success(function(data) { 
     $('#bodyText').html(data); 
    }); 

    response.complete(function() { 
     alert('ajax complete'); 
    }); 

}); 

我的服务看起来像这样

namespace AjaxTest.Ajax 
{ 
    #region 
using System.ComponentModel; 
using System.Web.Script.Serialization; 
using System.Web.Script.Services; 
using System.Web.Services; 

#endregion 

/// <summary> 
/// Summary for boat 
/// </summary> 
[WebService(Namespace = "http://quality/")] 
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 
[System.Web.Script.Services.ScriptService] 
public class Boat : WebService 
{ 
    #region Public Methods and Operators 

    /// <summary> 
    /// The Get Models method. 
    /// </summary> 
    [WebMethod] 
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)] 
    public void GetModels() 
    { 
     var models = Com.somedll.GetModels(); 
     var serializer = new JavaScriptSerializer(); 
     var response = models.Count != 0 
       ? serializer.Serialize(models) 
       : serializer.Serialize(new Error { Code = "500", Message = "Model Retrieval Failed" }); 
     this.Context.Response.Clear(); 
     this.Context.Response.ContentType = "application/json"; 
     this.Context.Response.Flush(); 
     this.Context.Response.Write(response); 
    } 

    #endregion 
    } 
} 

我收到以下错误后HTTP标头已经发送服务器不能追加头。 看着萤火虫的请求似乎被发送多次至少为每个请求,任何人都可以帮助。请让我知道您是否需要更多信息

+2

Flush应该是最后一件事情?尝试交换顺序:this.Context.Response.Flush(); this.Context.Response.Write(response); – 2012-03-28 13:40:02

+0

@BobTodd仍然收到相同的错误**服务器在发送HTTP头之后无法附加头信息**真的很奇怪,谢谢你们的纠正 – Deviland 2012-03-28 13:50:03

在拨打Flush之前拨打Response.Write电话。

this.Context.Response.Write(response); 
    this.Context.Response.Flush(); 

UPDATE:您也可以尝试删除ContentType二传手,因为你已经指出你的反应类型是JSON。

+0

我已经删除了内容类型声明,这没有任何效果,我正在努力看到什么是错误的,页面看起来不错,响应(在你的帮助下)现在看起来不错。但我仍然得到错误? – Deviland 2012-03-28 14:00:33

你可以尝试剥回:

this.Context.Response.Clear(); 
     this.Context.Response.ContentType = "application/json"; 
     this.Context.Response.Flush(); 
     this.Context.Response.Write(response); 

只是:

this.Context.Response.Write(response); 

甚至

this.Context.Response.BufferOutput = true; 
this.Context.Response.Write(response); 
this.Context.Response.End(); 

编辑

这听起来像你可能会遇到这种情况:

  1. 你写的东西repsonse
  2. 你冲洗
  3. 代码触发一个错误,asp.net试图改写头,这是不允许的,因为通话以冲洗()已经写了标头

坚持一个尝试赶在那里,看看是否有什么引发。

+0

我已经试过这个,并且已经证实在我的网络服务中没有错误在框中打勾:)。这导致我再次检查JavaScript,并且当我从此处移除contentType时,我将数据识别为JSON,但我仍然获得FireBug中显示的递归我不知道为什么,但现在响应已更改为** 401未经授权**全部6个电话。只是**重申我只是打电话给服务** – Deviland 2012-03-28 14:24:34