一、创建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测试: