利用jQuery以及PostMan測試WCF RestFul服務


一、創建WCF RestFul接口:

[OperationContract]
        [WebInvoke(Method = "*",
                    RequestFormat = WebMessageFormat.Json,
                    ResponseFormat = WebMessageFormat.Json,
                    UriTemplate = "SaveBook/{id}")]
        string SaveBook(Book book, string id);
public string SaveBook(Book book, string id)
{
  Book newBook = book;
  return "id =" +newBook.BookId;
}
public class Book
{
    public int BookId { get; set; }
    public string ISBN { get; set; }
    public string Title { get; set; }
}

二、用PostMan測試rest接口:

 

 

三、利用jQuery前端請求接口:

如果jQuery所在的項目與WCF Rest服務不在一個項目中,就構成了跨域。解決跨域的方式有很多種,這里不再詳述,解決辦法是可以在WCF服務中增加一個Global文件,具體關鍵代碼如下(可參考:

https://blog.csdn.net/blueblood7/article/details/73604644):

protected void Application_BeginRequest(object sender, EventArgs e)
        {
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
            if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
            {
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "POST, PUT, DELETE");

                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
                HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
                HttpContext.Current.Response.End();
            }
        }

前端代碼如下,記住Content-Type 類型為"application/json; charset=utf-8",因為接口要接受的是json數據

 1 var bookData = {
 2             "BookId": 200,
 3             "ISBN": "32334833425543",
 4             "Title": "WCF RESTful Service by Example"
 5         };
 6         $.ajax({
 7             type: "POST",
 8             url: "http://localhost:7909/Test.svc/SaveBook/200",
 9             data: JSON.stringify(bookData),
10             contentType: "application/json; charset=utf-8",
11             dataType: "json",
12             processData: true,
13             success: function (data, status, jqXHR) {
14                 alert("success…" + data);
15             },
16             error: function (xhr) {
17                 alert(xhr.responseText);
18             }
19         });

 如果需要傳入多個json(在后台轉換為類),可將這些json組裝在一個json對象中,如前端傳的json字符串如果為以下內容,則后台需要對fxtype、inoutparams、fxdk等類封裝到一個類中進行反序列化。

{
    "fxtype": {
        "fxtypeName": "規划分析(調整完善后)",
        "fxtypeGUID": "fb5a465c-c918-481c-a1e4-074d9c8836d3",
        "fxtypeDesp": "2010-2020規划分析(調整完善后),返回待分析地塊疊加的面積匯總信息以及明細圖斑信息",
        "fxtypeClassName": "Gisq.Canton.GHAnalysis.Extend.GH_TZWSH_Analysis"
    },
    "inoutparams": {
        "inparams": [{
            "paramname": "建設用地管制區圖層名稱",
            "paramvalue": "BASESDE.JSYDGZQ"
        }, {
            "paramname": "建設用地管制區圖層數據庫連接參數",
            "paramvalue": "sde:oracle11g:192.168.1.13/tx|basesde|basesde"
        }, {
            "paramname": "土地用途分區圖層名稱",
            "paramvalue": "BASESDE.TDYT"
        }, {
            "paramname": "土地用途分區圖層數據庫連接參數",
            "paramvalue": "sde:oracle11g:192.168.1.13/tx|basesde|basesde"
        }, {
            "paramname": "期末地類圖斑圖層名稱",
            "paramvalue": "BASESDE.QMDLTB"
        }, {
            "paramname": "期末地類圖斑圖層數據庫連接參數",
            "paramvalue": "sde:oracle11g:192.168.1.13/tx|basesde|basesde"
        }],
        "outtables": [{
            "tablename": "jsydgzqintersectdetails",
            "tablealias": "建設用地管制區疊加結果明細表",
            "tabletype": "shape_polygon",
            "outfield": [],
            "outrow": []
        }, {
            "tablename": "tdytfqintersectdetails",
            "tablealias": "土地用途分區疊加結果明細表",
            "tabletype": "shape_polygon",
            "outfield": [],
            "outrow": []
        }, {
            "tablename": "qmdltbintersectdetails",
            "tablealias": "期末地類圖斑疊加結果明細表",
            "tabletype": "shape_polygon",
            "outfield": [],
            "outrow": []
        }]
    },
    "fxdk": [{
        "dkid": "1234567",
        "dkname": "abdcd",
        "dkzb": {
            "spatialReference": {
                "wkt": "PROJCS[\"CGCS2000 3 Degree GK CM 113E\",GEOGCS[\"GCS_China_Geodetic_Coordinate_System_2000\",DATUM[\"D_China_2000\",SPHEROID[\"CGCS2000\",6378137.0,298.257222101]],PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]],PROJECTION[\"Gauss_Kruger\"],PARAMETER[\"False_Easting\",700000.0],PARAMETER[\"False_Northing\",0.0],PARAMETER[\"Central_Meridian\",113.0],PARAMETER[\"Scale_Factor\",1.0],PARAMETER[\"Latitude_Of_Origin\",0.0],UNIT[\"Meter\",1.0]]"
            },
            "rings": [
                [
                    [715218.70251464844, 2557695.51171875],
                    [715106.43530273438, 2557473.3660888672],
                    [714941.61767578125, 2557683.5682983398],
                    [715235.42327880859, 2558017.9810791016],
                    [715218.70251464844, 2557695.51171875]
                ]
            ]
        }
    }, {
        "dkid": "7654321",
        "dkname": "bdsd",
        "dkzb": {
            "spatialReference": {
                "wkt": "PROJCS[\"CGCS2000 3 Degree GK CM 113E\",GEOGCS[\"GCS_China_Geodetic_Coordinate_System_2000\",DATUM[\"D_China_2000\",SPHEROID[\"CGCS2000\",6378137.0,298.257222101]],PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]],PROJECTION[\"Gauss_Kruger\"],PARAMETER[\"False_Easting\",700000.0],PARAMETER[\"False_Northing\",0.0],PARAMETER[\"Central_Meridian\",113.0],PARAMETER[\"Scale_Factor\",1.0],PARAMETER[\"Latitude_Of_Origin\",0.0],UNIT[\"Meter\",1.0]]"
            },
            "rings": [
                [
                    [715992.62927246094, 2557578.4672851562],
                    [715961.57672119141, 2557332.4348754883],
                    [715765.70648193359, 2557466.2000732422],
                    [715992.62927246094, 2557578.4672851562]
                ]
            ]
        }
    }, {
        "dkid": "12345672222",
        "dkname": "abdcd2222",
        "dkzb": {
            "spatialReference": {
                "wkt": "PROJCS[\"CGCS2000 3 Degree GK CM 113E\",GEOGCS[\"GCS_China_Geodetic_Coordinate_System_2000\",DATUM[\"D_China_2000\",SPHEROID[\"CGCS2000\",6378137.0,298.257222101]],PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]],PROJECTION[\"Gauss_Kruger\"],PARAMETER[\"False_Easting\",700000.0],PARAMETER[\"False_Northing\",0.0],PARAMETER[\"Central_Meridian\",113.0],PARAMETER[\"Scale_Factor\",1.0],PARAMETER[\"Latitude_Of_Origin\",0.0],UNIT[\"Meter\",1.0]]"
            },
            "rings": [
                [
                    [715218.70251464844, 2557695.51171875],
                    [715106.43530273438, 2557473.3660888672],
                    [714941.61767578125, 2557683.5682983398],
                    [715235.42327880859, 2558017.9810791016],
                    [715218.70251464844, 2557695.51171875]
                ]
            ]
        }
    }]
}

 四、利用postman測試傳入內容為字符串的接口:

WCF Restful代碼(注意BodyStyle=WebMessageBodyStyle.WrappedRequest):

[OperationContract]
        [WebInvoke(Method = "*", UriTemplate = "/get_yzfxclass", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
        string get_yzfxclass(string ExtendClassName);
public string get_yzfxRst(WCFInputParams wcffxrst)
        {
            string strReturnMessage = string.Empty;
            Hashtable htResult = new Hashtable();
            try
            {
                ...
            }
            catch (Exception err)
            {
                htResult["outTables"] = new List<OutTable>();
                htResult["Error"] = err.ToString();
            }
            IsoDateTimeConverter pIsoDateTimeConverter = new IsoDateTimeConverter();
            pIsoDateTimeConverter.DateTimeFormat = "yyyy-MM-dd";
            strReturnMessage = Newtonsoft.Json.JsonConvert.SerializeObject(htResult);
            return strReturnMessage;

        }

利用postman測試:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM