2012-03-28 123 views
2

我的應用程序中有一個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

回答

2

在撥打Flush之前撥打Response.Write電話。

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

UPDATE:您也可以嘗試刪除ContentType二傳手,因爲你已經指出你的反應類型是JSON。

+0

我已經刪除了內容類型聲明,這沒有任何效果,我正在努力看到什麼是錯誤的,頁面看起來不錯,響應(在你的幫助下)現在看起來不錯。但我仍然得到錯誤? – Deviland 2012-03-28 14:00:33

1

你可以嘗試剝回:

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