본문 바로가기
프로그래밍/C#

C# 웹 서비스 확장 응용하기

by zoo10 2011. 4. 19.

환경 : visual studio 2010, .NET 4, iis7.0, windows 7 Enterprise K

이전 아티클을 먼저 확인해야 함
http://findfun.tistory.com/C# 웹 서비스 만들기 및 테스트

작업 내용

웹 서비스에 새로운 메소드 추가
- setMsg(string msg) : 메시지를 받아서 세션변수에 저장
- getMsg() : 세션변수에 저장된 메시지를 리턴

윈폼에 컨트롤 추가
- 텍스트 박스
- 버튼 추가

텍스트 박스에 입력된 내용을 버튼 클릭 시 웹 서비스 함수로 전달 
세션변수에 담았다가 꺼내서 메시지 창으로 출력


웹 서비스 추가하기

1. visual studio 2010 실행 > 웹 사이트 열기 > webservice_test 선택
2. 솔루션 탐색기 오른쪽 클릭 > 새 항목 추가 > visual c# 선택
3. 웹 서비스 선택 > 이름에 Echo.asmx 입력 > 다른 파일에 코드 입력 선택 > 추가
4. 솔루션 탐색기 App_Code에 Echo.cs 파일 생성 확인
5. Echo.asmx 파일 추가 확인
6. Echo.cs 파일 코드보기로 열기
7. 코드 추가

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

/// 
/// Echo의 요약 설명입니다.
/// 
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// ASP.NET AJAX를 사용하여 스크립트에서 이 웹 서비스를 호출하려면 다음 줄의 주석 처리를 제거합니다. 
// [System.Web.Script.Services.ScriptService]
public class Echo : System.Web.Services.WebService {

    public Echo () {

        //디자인된 구성 요소를 사용하는 경우 다음 줄의 주석 처리를 제거합니다. 
        //InitializeComponent(); 
    }

    [WebMethod(Description = "세션 사용하기", EnableSession = true)]
    public void setMsg(string msg) {
        HttpContext.Current.Session["mStrMsg"] = msg;
    }

    [WebMethod(EnableSession = true)]
    public string getMsg() {
        string rVal = "";

        if (HttpContext.Current.Session["mStrMsg"] != null)
            rVal = HttpContext.Current.Session["mStrMsg"].ToString();

        return rVal;
    }

    [WebMethod]
    public string HelloWorld() {
        return "Hello World";
    }
    
}
8. ctrl + F5 로 빌드 및 실행


응용 프로그램 만들기

1. visual studio 실행
2. 파일 > 프로젝트 열기
3. WebServiceTest 프로젝트 선택
4. 솔루션 탐색기에서 프로젝트 명 오른쪽 클릭 > 서비스 참조 추가 > 하단 고급 버튼 클릭
5. 서비스 참조 설정 대화상자 하단 웹 참조 추가 버튼 클릭
6. 로컬 컴퓨터의 웹 서비스 링크 클릭
7. Echo 링크 클릭 > 이 URL에서 찾은 웹 서비스 창에 setMsg, getMsg 함수가 추가되었는지 확인
8. 오른쪽에 참조 추가 클릭
9. 솔루션 탐색기에 Web Reference 항목 추가되었는지 확인 > 하위에 Ehco 추가 되었는지 확인
(프로젝트 속성 > 설정 탭에서 확인할 수 있음)
10. 폼에 텍스트박스와 버튼 하나 추가

11. 버튼을 더블 클릭하여 소스 추가
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;

namespace WebServiceTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            localhost.Service ls = new localhost.Service();
            string txt = ls.HelloWorld();
            MessageBox.Show(txt);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                Echo.Echo echo = new Echo.Echo();
                echo.CookieContainer = new CookieContainer();

                string msg = textBox1.Text;
                echo.setMsg(msg);

                string echoMsg = echo.getMsg();
                if (echoMsg == null) echoMsg = "";

                MessageBox.Show(echoMsg);
            }
            catch (Exception er)
            {
                MessageBox.Show(er.Message);
            }
        }
    }
}
12. ctrl + F5로 빌드 및 실행
13. 웹서비스 호출 버튼 클릭 > Hello World 메시지 창 출력되면 완료

핵심 내용

- 웹 메소드 추가 방법 습득
- 웹 서비스에서 세션 사용법 습득
: [webMethod(EnabledSession=true)]
- 윈 폼에서 웹 세션 변수 사용법 습득
: System.Net.CookieContainer 클래스 사용