유쾌한 냐옹이입니다.
Asp.net 웹페이지에서 jquery 및 jsonp를 이용하여 다른 IP의 웹서비스를 사용하는 방법입니다.
아래 예제를 토대로 설명 시작합니다.
1.ClientScript 쪽 소스
<script type="text/xxxxjavascript" src="jquery-1.6.2.js"></script> <script type="text/xxxxjavascript" src="jquery-ui-1.8.16.custom.min.js"></script><script type="text/xxxxjavascript" language="xxxxjavascript"> function Push() { $.ajax({ url: "http://192.168.10.102/TestApp/DBManager.asmx/Hello", data: "{}", dataType: 'jsonp', success: function (data) { alert("성공 : " + data.d); }, error: function (result) { alert("에러 : " + result.status + ' ' + result.statusText); } }); }</script><!-- 컨트롤 정의 -->
<input id="Button1" type="button" value="button" [안내]태그제한으로등록되지않습니다-xx[안내]태그제한으로등록되지않습니다-xxonclick="Push()" /></h2>
위 구문 중 $.ajax부분이 비동기로 호출하는 구문이고 url에 해당 웹서비스의 asmx파일 및 슬래시('/')뒤에 함수명을 적어주시면 됩니다. data부분은 매개변수를 입력하면 됩니다.
dataType을 jsonp로 하였기때문에 다른IP의 웹서비스를 호출할 수 있게 됩니다.
2. 웹서비스 쪽 소스
DLL 파일로 아래 ContentTypeHttpModule을 생성합니다.
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Text;
- using System.Web;
-
- namespace ContentTypeHttpModule
- {
- public class ContentTypeHttpModule : IHttpModule
- {
- private const string JSON_CONTENT_TYPE = "application/json; charset=utf-8";
-
- #region IHttpModule Members
- public void Dispose()
- {
- }
-
- public void Init(HttpApplication app)
- {
- app.BeginRequest += OnBeginRequest;
- app.ReleaseRequestState += OnReleaseRequestState;
- }
- #endregion
-
- public void OnBeginRequest(object sender, EventArgs e)
- {
- HttpApplication app = (HttpApplication)sender;
- HttpRequest resquest = app.Request;
- if (!resquest.Url.AbsolutePath.Contains("DBManager.asmx")) return;
-
- 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;
- HttpResponse response = app.Response;
- if (app.Context.Request.ContentType != JSON_CONTENT_TYPE) return;
-
- response.Filter = new JsonResponseFilter(response.Filter);
- }
- }
-
- public class JsonResponseFilter : Stream
- {
- private readonly Stream _responseStream;
- private long _position;
-
- public JsonResponseFilter(Stream responseStream)
- {
- _responseStream = responseStream;
- }
-
- 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)
- {
- string strBuffer = Encoding.UTF8.GetString(buffer, offset, count);
- strBuffer = AppendJsonpCallback(strBuffer, HttpContext.Current.Request);
- byte[] data = Encoding.UTF8.GetBytes(strBuffer);
- _responseStream.Write(data, 0, data.Length);
- }
-
- private string AppendJsonpCallback(string strBuffer, HttpRequest request)
- {
- return request.Params["callback"] + "(" + strBuffer + ");";
- }
-
- 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);
- }
- }
- }
3. 만들어진 ContentTypeHttpModule DLL을 참조추가로 하여 웹서비스 프로젝트에 추가 해 줍니다.

위 예에서는 ICSService쪽 참조에 참조추가가 되겠습니다.
4. 웹서비스의 Web.config파일에 httpModules속성에 ContentTypeHttpModule을 사용함을 명시합니다.
Web.config 파일의 <system.web> 하위에 DLL을 참조하도록 아래 부분을 추가 해 준다.
<httpModules>
<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add name="ContentTypeHttpModule" type="ContentTypeHttpModule.ContentTypeHttpModule, ContentTypeHttpModule"/>
</httpModules>
5. 웹서비스에 UseHttpGet = true 속성과 ResponseFormat = ResponseFormat.Json 부분을 추가 해 줍니다.
[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public string Hello()
{
return "Hello Nyaonge~";
}
매개변수가 있는 웹서비스의 함수를 호출 하려면 호출 시 아래와 같은 순서로 한다.
<1>. 호출하고자 하는 웹페이지에서 jquery의 [json2.js] 파일을 추가 한다. (JSON 객체 사용하기 위함)
<2>. 사용할 때 아래와 같이 작성한다.
data : { 웹서비스의 매개변수명 : JSON.stringify(매개변수값) },
function Push() {
$.ajax({
url: "http://192.168.10.102/TestApp/DBManager.asmx/SelectPresetByCameraCode_Web",
data: { CameraCode : JSON.stringify("1") },
dataType: "jsonp",
success: function (data) {
alert("성공 : " + data.d);
},
error: function (result) {
alert("에러 : " + result.status + ' ' + result.statusText);
}
});
위는 제가 만들어 본 예제소스고 원본 예제소스를 올립니다.
2146.JSONP-Prototype (2).zip
첫댓글 짱...~~~~ GOOD
알려주셔서 빨리해결했어요