2012-09-21 3 views
2

수많은 예제를 시도 했으므로 작동하지 않습니다.Jsonp를 사용하여 Cross Domain Asp.Net 웹 서비스를 호출하십시오.

내가 크로스 도메인 asp.net 웹 서비스를 호출하지만, 다음과 같은 오류마다 다시 얻으려고 :

jQuery18105929389187970706_1348249020199이

여기 내 웹 서비스의를 호출되지 않은

을 :

[WebService(Namespace = "http://www.mywebsite.org/")] 
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 
[System.ComponentModel.ToolboxItem(false)] 
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
// [System.Web.Script.Services.ScriptService] 
[ScriptService] 
public class DataService : System.Web.Services.WebService 
{ 
    [WebMethod] 
    [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)] 
    public string GetIncidentsByAddress() 
    { 
     return "It worked!"; 
    } 
} 

Json을 처리 할 My HttpModule :

public class JsonHttpModule : IHttpModule 
    { 
     private const string JSON_CONTENT_TYPE = "application/json; charset=utf-8"; 

     public void Dispose() 
     { 
     } 

     public void Init(HttpApplication app) 
     { 
      app.BeginRequest += OnBeginRequest; 
      app.ReleaseRequestState += OnReleaseRequestState; 
     } 

     bool _Apply(HttpRequest request) 
     { 
      if (!request.Url.AbsolutePath.Contains(".asmx")) return false; 
      if ("json" != request.QueryString.Get("format")) return false; 
      return true; 
     } 

     public void OnBeginRequest(object sender, EventArgs e) 
     { 
      HttpApplication app = (HttpApplication)sender; 

      if (!_Apply(app.Context.Request)) return; 

      // correct content type of request 
      if (string.IsNullOrEmpty(app.Context.Request.ContentType)) 
      { 
       app.Context.Request.ContentType = JSON_CONTENT_TYPE; 
      } 
     } 

     public void OnReleaseRequestState(object sender, EventArgs e) 
     { 
      HttpApplication app = (HttpApplication)sender; 

      if (!_Apply(app.Context.Request)) return; 

      // apply response filter to conform to JSONP 
      app.Context.Response.Filter = 
       new JsonResponseFilter(app.Context.Response.Filter, app.Context); 
     } 
    } 

    public class JsonResponseFilter : Stream 
    { 
     private readonly Stream _responseStream; 
     private HttpContext _context; 

     public JsonResponseFilter(Stream responseStream, HttpContext context) 
     { 
      _responseStream = responseStream; 
      _context = context; 
     } 

     //... 

     public override void Write(byte[] buffer, int offset, int count) 
     { 
      var b1 = Encoding.UTF8.GetBytes(
       _context.Request.Params["callback"] + "("); 
      _responseStream.Write(b1, 0, b1.Length); 
      _responseStream.Write(buffer, offset, count); 
      var b2 = Encoding.UTF8.GetBytes(");"); 
      _responseStream.Write(b2, 0, b2.Length); 
     } 

     //... 
    } 

내 Web.config를 말했다 HttpModule의 :

<add name="JSONAsmx" type="JsonHttpModule, App_Code"/> 

그리고 마지막으로 내 jQuery를 호출 :

<script src="js/jquery.jmsajax.min.js" type="text/javascript"></script> 
<script src="js/jquery-1.8.1.min.js" type="text/javascript"></script> 

<script type="text/javascript"> 

    $.jmsajaxurl = function(options) { 
     var url = options.url; 
     url += "/" + options.method; 
     if (options.data) { 
      var data = ""; for (var i in options.data) { 
       if (data != "") 
        data += "&"; data += i + "=" + 
      msJSON.stringify(options.data[i]); 
      } 
      url += "?" + data; data = null; options.data = "{}"; 
     } 
     return url; 
    }; 

    $(function() { 
     var url = $.jmsajaxurl({ 
      url: "http://www.mywebsite.org/apps/IncidentReportingService/DataService.asmx", 
      method: "GetIncidentsByAddress", 
      data: {} 
     }); 

     $.ajax({ 
      cache: false, 
      dataType: "jsonp", 
      success: function(data) { successCallback(data); }, 
      error:function(xhr, status, errorThrown) { debugger;}, 
      url: url + "&format=json" 
     }); 

    }); 

    function successCallback(data) { 
     debugger; 
     $.each(data, function(i, item) { 
      $("#tweets ul").append("<li>" + item.text + "</li>"); 
     }); 
    }; 

어떤 아이디어?

+0

다음과 같이 반환 된 데이터를 분석하는 시도 . typicall jsonp가 콜백 매개 변수를 전달해야했습니다. 예 : $ .ajax ({ url : 'http://myurl.com/Api/test/?callback=?', 유형 : "POST", data : $ .toDictionary (myobj), dataType : "json", jsonpCallback : "응답" }); – atbebtg

답변

0

글쎄, 내 HttpModule이 모든 방법으로 구현되지 않는 것으로 보입니다. 거기에 겹쳐 쓰지 않은 메소드가 있고 전체 웹 서비스가 작동하지 않게하는 방법이 있습니다.

난 다음 이제 모든에 변경이 작동합니다

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.IO; 
using System.Text; 

public class JsonHttpModule : IHttpModule 
{ 
    private const string JSON_CONTENT_TYPE = "application/json; charset=utf-8"; 

    public void Dispose() 
    { 
    } 

    public void Init(HttpApplication app) 
    { 
     app.BeginRequest += OnBeginRequest; 
     app.ReleaseRequestState += OnReleaseRequestState; 
    } 

    bool _Apply(HttpRequest request) 
    { 
     if (!request.Url.AbsolutePath.Contains(".asmx")) return false; 
     if ("json" != request.QueryString.Get("format")) return false; 
     return true; 
    } 

    public void OnBeginRequest(object sender, EventArgs e) 
    { 
     HttpApplication app = (HttpApplication)sender; 

     if (!_Apply(app.Context.Request)) return; 

     // correct content type of request 
     if (string.IsNullOrEmpty(app.Context.Request.ContentType)) 
     { 
      app.Context.Request.ContentType = JSON_CONTENT_TYPE; 
     } 
    } 

    public void OnReleaseRequestState(object sender, EventArgs e) 
    { 
     HttpApplication app = (HttpApplication)sender; 

     if (!_Apply(app.Context.Request)) return; 

     // apply response filter to conform to JSONP 
     app.Context.Response.Filter = 
      new JsonResponseFilter(app.Context.Response.Filter, app.Context); 
    } 
} 

public class JsonResponseFilter : Stream 
{ 
    private readonly Stream _responseStream; 
    private HttpContext _context; 
    private long _position; 

    public JsonResponseFilter(Stream responseStream, HttpContext context) 
    { 
     _responseStream = responseStream; 
     _context = context; 
    } 

    public override bool CanRead { get { return true; } } 

    public override bool CanSeek { get { return true; } } 

    public override bool CanWrite { get { return true; } } 

    public override long Length { get { return 0; } } 

    public override long Position { get { return _position; } set { _position = value; } } 

    public override void Write(byte[] buffer, int offset, int count) 
    { 
     var b1 = Encoding.UTF8.GetBytes(
      _context.Request.Params["callback"] + "("); 
     _responseStream.Write(b1, 0, b1.Length); 
     _responseStream.Write(buffer, offset, count); 
     var b2 = Encoding.UTF8.GetBytes(");"); 
     _responseStream.Write(b2, 0, b2.Length); 
    } 

    public override void Close() 
    { 
     _responseStream.Close(); 
    } 

    public override void Flush() 
    { 
     _responseStream.Flush(); 
    } 

    public override long Seek(long offset, SeekOrigin origin) 
    { 
     return _responseStream.Seek(offset, origin); 
    } 

    public override void SetLength(long length) 
    { 
     _responseStream.SetLength(length); 
    } 

    public override int Read(byte[] buffer, int offset, int count) 
    { 
     return _responseStream.Read(buffer, offset, count); 
    } 
} 
1

는 JSON 내가 콜백 매개 변수가 아약스 호출에 전달되는 표시되지 않습니다

success: function(data) { 
    data = JSON.parse(data); 
    // Do work with the data 
} 
관련 문제