我应该使用 WCF 还是直接使用 Razor/cshtml 文件来创建服务?
我有一个旧的 Web 表单,需要使用一些 ajax 功能进行扩展。我已升级到 .net 4,但想知道创建新服务时应采用什么方法。
我在编写 wcf 服务方面没有太多经验,而且使用简单的 cshtml 文件编写服务似乎要简单得多,如下所示:
@{
var db = Database.Open("MyConnectionString);
var data = db.Query("SELECT * FROM MyTable WHERE Col1 = @0", '123');
Json.Write( new { results=data}, Response.Output);
}
与创建 wcf 服务相比,使用此策略有哪些陷阱?
帮助
感谢拉尔西的
I've got an old web forms that is to be extended with some ajax functionality. I've upgraded to .net 4, but wondering what approach to go for when creating new services.
I don't have to much experience with writing wcf services, and it seems way much simpler just writing a the service using a simple cshtml file like this:
@{
var db = Database.Open("MyConnectionString);
var data = db.Query("SELECT * FROM MyTable WHERE Col1 = @0", '123');
Json.Write( new { results=data}, Response.Output);
}
What are the pitfalls using this strategy compared to creating a wcf service?
Thanks for any help
Larsi
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
根据您对 CodeCaster 的评论,我认为您混淆了 Web 服务和 Web 方法的概念。如果您所做的只是将 Ajax 添加到应用程序中,那么您需要 Web 方法,即返回 json 的操作方法。而且,由于您使用的是网页,因此您的方法是完全有效的。
Based on your comment to CodeCaster, I think you're confusing the concepts of web service and web method. If all you're doing is adding Ajax to your app, then you want web methods, which are action methods that return json. And, since you're using webpages, then your approach is perfectly valid.
使用 WCF,您可以:
优点?
Response.Write
全部或不返回任何您喜欢的内容)并且可能还有很多其他事情我会忘记。
Using WCF, you could do:
The advantages?
Response.Write
all or nothing you like)And there are probably a ton of other things I'd forget.
其他响应中未提及的一个考虑因素是 Json.Write 的性能。它适用于带有几列的小型记录集,但我注意到它的速度相当慢,即使只有 ~70 条记录和 10 列。这在您正在“Ajaxifying”的 Web 应用程序的上下文中尤其重要,您通常会尝试使应用程序对用户交互更加敏感。在这些情况下,我通常会使用 Json.Write 只是为了获得概念验证,但最终会返回并修改 razor 页面以循环返回的记录并使用 StringBuilder 构建 JSON 字符串并写入到输出。
我不知道 WCF 的性能,但如果它比循环字符串生成器更快,您可以将其添加到上面的好处列表中(权衡设置它的复杂性)。
One consideration not mentioned in the other responses is the performance of Json.Write. It works well for small record sets w/ a few columns, but I've noticed that it is appreciably slow w/ even as few as ~70 records and 10 columns. This is especially important in the context of a web application that you are "Ajaxifying" where you typically are trying to make the application more responsive to user interactions. In these cases I'll typically use Json.Write just to get a proof of concept working, but then will end up going back and modifying the razor page to loop through the returned records and building the JSON string w/ a StringBuilder and write that to the output.
I don't know the performance of WCF, but if it's faster than looping a string builder, you might add that to the list of benefits above (to be weighed against the complexity of setting it up).