본문 바로가기

Web_Application/ASP.NET MVC

[ASP.NET MVC] 도로명주소 검색하기 소스





도로명주소 안내시스템(http://www.juso.go.kr/openIndexPage.do) 의 open api 연계가이드를 바탕으로 작성하였습니다.

가이드에서 제공하는 url에 직접 ajax 호출시 IE 저버전(7,8,9)에서 XSS가 발생함.

jQuery 의 권고 ( $.support.cors = true; ) 적용시 보안 컨텐츠경고창이 뜨게되니 이방법도 패스~

Ajax 호출부 URL을 로컬 경로로 변경하고 HttpWebRequest 로 호출 후 string 으로 결과값 반환하는 방식으로 변경



Controller
      
public string RoadAddress(string confmKey, int currentPage = 1, int countPerPage = 10, string keyword = "")
{
    string responseFromServer;

    try
    {
        HttpWebRequest httpRequest = (HttpWebRequest)HttpWebRequest.Create("http://www.juso.go.kr/addrlink/addrLinkApiTest.do");
        httpRequest.Method = WebRequestMethods.Http.Post;
        httpRequest.ContentType = "application/x-www-form-urlencoded";
        HttpWebResponse response = (HttpWebResponse)httpRequest.GetResponse();
        StreamReader reader = new StreamReader(response.GetResponseStream());
        responseFromServer = reader.ReadToEnd();
    }
    catch (Exception ex) 
    {
        responseFromServer = String.Format("errorMessage : {0}", ex.Message);
    }

    return responseFromServer;
}

View
@using (Html.BeginForm("Index", "Address", FormMethod.Post, new { @class = "form-horizontal", @id = "address_form" }))
{
    <input type="hidden" name="currentPage" value="1">
    <input type="hidden" name="countPerPage" value="5">
    <input type="hidden" name="confmKey" value="12gws43hdfghfh24y6345yadsfhbfdgfsd234tdsfgbvfdg">
    <div class="row">
        <div class="col-lg-6">
            <div class="input-group">
                <span class="input-group-addon">검색어</span>
                <input type="text" class="form-control" name="keyword">
                <span class="input-group-btn">
                    <button class="btn btn-default" type="button" onclick="javascript: getAddrLoc();">검색</button>
                </span>
            </div><!-- /input-group -->
        </div><!-- /.col-lg-5 -->
    </div><!-- /.row -->
}
<!-- 검색 결과 목록-->
<div id="list" class="col-lg-12"></div>    



javascript( jQuery-1.10.2.js )
<script type="text/javascript">
function getAddrLoc()
{
    $.ajax({
        url: "/Address/RoadAddress",
        type: "post",
        data: $("#address_form").serialize(),
        dataType: "text",
        success: function (result)
        {
            xmlStr = $.parseXML(result);

            $("#list").html("");
            var errCode = $(xmlStr).find("errorCode").text();
            var errDesc = $(xmlStr).find("errorMessage").text();

            if (errCode != "0"){
                alert(errCode + "=" + errDesc);
            } else {
                if (xmlStr != null)
                    makeList(xmlStr);
                else
                    makeList(xmlStr);
            }
        },
        error: function (xhr, status, error)
        {
            alert("에러발생 : xhr - " + xhr + " | status - " + status + " | error - " + error);
        }
    });
}

function makeList(xmlStr)
{
    var htmlStr = "";
    htmlStr += "<table class=\"table table-striped table-hover \">";
    htmlStr += "<thead>";
    htmlStr += "<tr>";
    htmlStr += "<th>선택</th>";
    htmlStr += "<th>도로명주소</th>";
    //htmlStr += "<th>도로상세1</td>";
    //htmlStr += "<th>도로상세2</td>";
    htmlStr += "<th>지번주소</th>";
    //htmlStr += "<th>영문주소</td>";
    htmlStr += "<th>우편번호</th>";
    htmlStr += "</tr>";
    htmlStr += "</thead>";
    htmlStr += "<tbody>";
    $(xmlStr).find("juso").each(function () {
        htmlStr += "<tr>";
        htmlStr += "<td><input type=\"radio\" name=\"address_data\" value=\"" + $(this).find('zipNo').text() + "\"/></td>";
        htmlStr += "<td><small><p><b>" + $(this).find('roadAddr').text() + "</b></p></td>";
        htmlStr += "<td><small><p>" + $(this).find('jibunAddr').text() + "</p></small></td>";
        //htmlStr += "<td>" + $(this).find('engAddr').text() + "</td>";
        htmlStr += "<td>" + $(this).find('zipNo').text() + "</td>";
        //htmlStr += "<td>" + $(this).find('admCd').text() + "</td>";
        //htmlStr += "<td>" + $(this).find('rnMgtSn').text() + "</td>";
        //htmlStr += "<td>" + $(this).find('bdMgtSn').text() + "</td>";
        htmlStr += "</tr>";
    });
    htmlStr += "</tbody>";
    htmlStr += "</table>";
    $("#list").html(htmlStr);
}

function enterSearch()
{
    var evt_code = (window.netscape) ? ev.which : event.keyCode;

    if (evt_code == 13)
    {
        event.keyCode = 0;
        getAddrLoc();
    }
}

</script>