2013-05-15 128 views
1

我的問題與描述的here非常類似。使用jquery和jsonp的ASP.NET跨域web服務調用錯誤

然而,在我的情況下,我得到500內部服務器錯誤的螢火:

請求格式是無法識別的URL在「/ HelloWorld的」意外結束。

我的asp.net 4.0 web服務調用是跨域的,並從超過十幾個其他網站的建議我相信我已經配置了一切,以便讓這種情況發生正確,但顯然我沒有。我究竟做錯了什麼?

我正在使用JSONP而不是JSON。如果所有內容都在同一臺服務器上,則Web服務按預期工作。我的問題是調用Web服務的HTML頁面的主機提供程序不允許服務器端代碼,否則我只是把所有內容放在一個地方並完成它!

下面

是我的代碼/標記:

的web.config:

<?xml version="1.0"?> 
    <configuration> 
    <system.webServer> 
    <httpErrors errorMode="Detailed"></httpErrors> 
    <asp scriptErrorSentToBrowser="true"></asp> 
    <modules> 
     <add name="ContentTypeHttpModule" 
        type="ContentTypeHttpModule.ContentTypeHttpModule, ContentTypeHttpModule" /> 
    </modules> 
    </system.webServer> 
    <system.web> 
    <customErrors mode="Off"></customErrors> 
    <compilation debug="true" targetFramework="4.0"/> 
    <trust level="Full"/> 
    <pages clientIDMode="Static"/> 
    <webServices> 
     <protocols> 
     <add name="HttpGet"/> 
     <add name="HttpPost"/> 
     </protocols> 
    </webServices> 
    <!--<httpModules> 
     <add name="ContentTypeHttpModule" 
        type="ContentTypeHttpModule.ContentTypeHttpModule, ContentTypeHttpModule" /> 
    </httpModules>--> 
    </system.web> 
</configuration> 

HTML文件的javascript:

function test() { 
      $.ajax({ 
       url: 'http://designonlinelettering.com/RenderImage.asmx/HelloWorld', 
       data: {}, 
       contentType: "application/json; charset=utf-8", 
       dataType: "jsonp", 
       success: function (result) { 
        var data = result.d; 
        alert(data); 
       }, 
       error: function (e) { 
        alert('error: ' + e.d); 
       } 
      }); 
     } 

Web服務代碼:

[WebMethod] 
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)] 
public string HelloWorld() 
{ 
return "Hello World"; 
} 

ContentTypeHttpModule代碼是從這個非常翔實blog,從中我得到了我的大部分方向的拍攝。如前所述

感謝您的幫助......

+1

的contentType和錯誤選項JSONP請求,僅供參考 –

+1

你所得到的錯誤是服務器端的,無關的jQuery。直接導航到'http:// designonlinelettering.com/RenderImage.asmx/HelloWorld',你會看到。 –

回答

1

,如果你在瀏覽器中查看http://designonlinelettering.com/RenderImage.asmx/HelloWorld你會看到錯誤。添加一個?callback = x並沒有幫助。它只會爲正確設置了數據/響應類型的POST請求返回JSON。

ASMX有問題,並且不會爲GET請求返回JSON ...您最好的選擇是使用ASHX和Response.Render JSON(我推薦使用JSON.Net作爲編碼器)。不需要爲$就

... 
using Newtonsoft.Json; 
using Newtonsoft.Json.Converters; 
using Newtonsoft.Json.Linq; 
... 
    var ret = JsonConvert.SerializeObject(
    objectToReturn 
    ,new IsoDateTimeConverter() 
    ,new DataTableConverter() 
    ,new DataSetConverter() 
); 
    //only need the datatable, and dataset converters if you're returning those types 

    //jsonp should have a callback on the querystring, in your jquery 
    // request append "pathto.ashx?callback=?" 
    context.Response.ContentType = "application/javascript"; 
    context.Response.Write(string.format(
    "{0}({1});" 
    ,context.Request.QueryString["callback"] 
    ,ret 
)); 
... 
+1

謝謝!這工作完美。 – RoastBeast