开发者

JSON Web service with ASP.NET - from a frustrated php guy

开发者 https://www.devze.com 2023-04-11 01:41 出处:网络
I\'ve been a PHP developer for a few years now and have developed at least a dozen APIs using JSON. Create a url that does a task, and return json_encode($array)... Piece of cake...right?

I've been a PHP developer for a few years now and have developed at least a dozen APIs using JSON. Create a url that does a task, and return json_encode($array)... Piece of cake...right?

Now, I used to be a .net developer a while back (about 8 yrs ago) and I've been given the task to develop a small api/webservice for a client. I've been doing some reading on WCF and have been tinkering开发者_运维技巧 with it for a few hours now. My question is.. Is it me or is it incredibly over complicated to just run a RESTFUL query and return a block of JSON? In other words, why can't I just create an ASPX page that takes an array and encodes it as JSON and spits it out? Does it really HAVE to be WCF? Or even ASMX for that matter? Feels like overkill? No? Can someone offer a valid reson on why I need to go through the pain of WCF if I'm making a simple service that returns a few lines of JSON?


You can use WebMethods:

Using jQuery to directly call ASP.NET AJAX page methods

Code-behind:

public partial class _Default : Page 
{
  [WebMethod]
  public static string GetDate()
  {
    return DateTime.Now.ToString();
  }
}

Script:

$.ajax({
  type: "POST",
  url: "Default.aspx/GetDate",
  data: "{}",
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function(msg) {        
    // alert(msg.d);
  }
});
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号