开发者

C# Where to return JSON from

I have some JQuery / JSON features on a website I'm working on. These features are going to be used on a few different pages so I'm wondering where I should put the code that returns the JSON. From what I understand I basically have 3 options. I could create an ASHX fi开发者_C百科le, a web service ASMX or put a public static [webmethod] method on the page that's using the feature. Because I'm reusing these features I suspect the last option is not the correct one. What would be best practice in this scenario?


The serializer that ASMX ScriptServices and ASPX "page methods" (the static [WebMethod]) use is quite nice when you're working with JavaScript/jQuery - more flexible and correct than WCF's in several aspects - so don't let anyone make you feel bad about using these approaches. Someone will almost always point out that ASMX is "obsolete", but that doesn't really square with the fact that File > New > Web Service still creates an ASMX service and is still a first-class item in .NET 4. Simplicity is a feature, and ASMX is hard to beat in that department.

I would recommend against using an ASHX handler for returning JSON to the client-side, unless you're piping JSON strings back from a third-party service.

If you're returning your own server-side objects, it doesn't make sense to incur the extra code to manually convert to and from JSON when ScriptServices and page methods do it automatically. Even though it's very easy to use JavaScriptSerializer to do so, why complicate things with that extra code at the beginning and end of every endpoint?


If these are going to be used on a few pages, I would create a page under a common namespace in your solution which will hold your static web methods. Then you can call these webmethods from any page you like. I wouldn't really want do deal with the WCF design, setup and maintenance for your situation. Just my opinion though.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜