본문 바로가기
개발/ASP.NET

Web Form : API 기능 구축

by ispie 2019. 2. 1.

오래전에 ASP.NET Web Form 으로 만들어진 웹 어플리케이션 상에서 외부에서 호출할 API 기능을 추가하는 일이 있었기 때문에 그 내용을 정리해 보았습니다.

 

1. Global.asax 와 Global.asax.cs 의 확인 및 설정

 

1-1. Global.asax와 Global.asax.cs의 작성

※ Global.asax와 Global.asax.cs 가 해당 프로젝트에 존재하지 않을 경우 입니다.

 

아래의 순서로 Global.asax 파일을 생성합니다.

File -> New -> File -> Global Application Class

 

위의 처리로는 Global.asax 파일만 작성 되므로 Add -> Add New Item -> Class (Visual C#) 를 선택하여 ~/ 또는 ~/App_Code 등 해당 웹 어플리케이션의 서버 로직의 폴더 설정에 맞게 Global.asax.cs를 생성해 줍니다.

 

1-2. Global.asax.cs 에 API 호출을 할 URL를 설정

 

Global.asax

<%@ Application Language="C#" CodeBehind="Global.asax.cs" Inherits="Global" %>

기존 프로젝트에 Global.asax 가 있을 경우엔 그대로 두면 됩니다.

 

Global.asax.cs

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

public class Global : System.Web.HttpApplication
{
    protected void Application_Start(object sender, EventArgs e)
    {
        RegisterRoutes(System.Web.Routing.RouteTable.Routes);
        System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls | System.Net.SecurityProtocolType.Tls11 | System.Net.SecurityProtocolType.Tls12;
    }

    private static void RegisterRoutes(System.Web.Routing.RouteCollection routes)
    {
        routes.MapPageRoute("api1", "user/create", "~/api.aspx");
        routes.MapPageRoute("api2", "user/delete", "~/api.aspx");
    }
}

 

 

어플 기동시에 RegisterRoutes 설정을 참고하도록 Application_Start에 설정을 추가합니다.(10번째 줄)

RegisterRoutes에 API로 호출될 URL을 API 처리를 할 aspx에서 넘겨받도록 설정해 줍니다.(16, 17번째 줄)

※ 11번째 줄은 SSL/TLS의 설정입니다.

 

 

2. API 호출시에 해당 내용을 처리할 aspx를 작성

 

아래의 순서로 새로운 웹폼 화면을 작성합니다. (예시에서는 Api.aspx, Api.aspx.cs 로 합니다)

Add -> Add New Item -> Web Form (Visual C#)

 

Api.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Callback.aspx.cs" Inherits="Callback" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
        </div>
    </form>
</body>
</html>

aspx 파일은 작성 후 그대로 두시면 됩니다.(변경 없음)

 

Api.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.IO;
using System.Web.Script.Serialization;
using System.Web.Services;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

public partial class Api : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DoJob();
        }
    }

    private void DoJob()
    {
		// 결과 코드(리스펀스로 돌려줄 값)
		var resultCode = "OK";
		var message = "처리가 완료 되었습니다.";
		
        try
        {
            // 리퀘스트 패러미터의 취득
            var raws = Request.ContentEncoding.GetString(Request.BinaryRead(Request.ContentLength));

            if (Request.HttpMethod != "POST")
            {
                throw new Exception("HTTP 503 - HTTP Methods GET is disabled.");
            }

            if (string.IsNullOrEmpty(raws))
            {
                throw new Exception("HTTP 503 - Parameters are required.");
            }

            bool isProduction = Convert.ToBoolean(Defines.IsProduct);
			
			// API1
            if (Request.Url.LocalPath.Contains("/user/create"))
            {
                JObject obj = JObject.Parse(raws);

                // 패러미터(raws)
                resultStaffNo = (string)obj["user_name"];
				
				// 필요한 처리
				resultCode = "OK";// or NG or SKIP or ERR etc
                
            }
            else if (Request.Url.LocalPath.Contains("/staff/restore"))
            {
                JObject obj = JObject.Parse(raws);

                // 패러미터(raws)
                resultStaffNo = (string)obj["user_name"];
				
				// 필요한 처리
				resultCode = "OK";// or NG or SKIP or ERR etc
            }
        }
        catch (Exception ex)
        {
            resultCode = "ERR";
            message = ex.Message;
        }
        finally
        {
            Dictionary<string, object> resultData = new Dictionary<string, object>();
			resultData["result_code"] = resultCode;
			resultData["message"] = message;

            JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
            result = jsonSerializer.Serialize(resultData);

            Response.ClearContent();
            Response.ContentType = "text/json; charset=utf-8";
            Response.ContentEncoding = System.Text.Encoding.UTF8;
            Response.Write(result);
            Response.End();
        }
    }
}

 

주요 부분으로는 API의 패러미터 취득, JSON형식의 리스펀스 리턴 부분만 확인하시면 문제 없습니다.

1. 33번째 줄의 Request.ContentEncoding.GetString를 사용하여 API의 Raws 데이터를 취득합니다.

2. finally 내부는 처리 결과를 JSON으로 돌려주는 리스펀스 처리를 합니다.

 

API의 사양을 POST/raws(ex) url:user/create + raws:{"user_name":"name"}) 형식이 아닌 GET/query 형식(ex) url:user/create?user_name=name)으로  할 경우에는 33번 째 줄의 Request.ContentEncoding.GetString의 처리가 필요 없으며, 아래와 같이 개별 패러미터를 취득합니다.

// 패러미터 (QueryString) var userName = Request.QueryString["user_name"].ToString();

 

3. API 동작 확인

 

2번까지 작업한 웹 어플리케이션이 기동되어 있는 상태에서 Postman 에서 아래와 같이 설정해서 Send를 클릭합니다.

 

 

결과가 아래와 같이 JSON형식으로 표시되면 API 호출이 성공한 것입니다.

{     "result": "OK",     "message": "처리가 완료 되었습니다." }

 

관련 기사

C# : API 호출 방법

 

댓글