如何获得“服务”? ASP.NET MVC 中的页面?
MVC 新手:
我已经或多或少地解决了 MVC 的页面导航方面的问题。但假设我不想导航到视图,而是想从网站获得响应,例如通过向 http://mysite.com/Services/GetFoo/123 我想发出一个数据库请求来选择 ID 为 123 的 Foo
对象并返回它序列化为 XML。
你是怎么做到的?
MVC newbie here:
I've more or less worked out the page navigation aspect of MVC. But let's say I don't want to navigate to a View, but rather I want to get a response out of the web site, e.g. by sending a request to http://mysite.com/Services/GetFoo/123 I want to make a database request to select a Foo
object with ID 123 and return it serialized as XML.
How do you do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我会编写一个自定义操作结果:
然后在我的控制器中:
如果这个
return new XmlResult(foo);
在你看来很难看,你可以有一个扩展方法:然后:
I would write a custom action result:
and then in my controller:
And if this
return new XmlResult(foo);
feels ugly to your eyes, you could have an extension method:and then:
听起来您想创建一个 REST API。
看看午睡将完成所有繁重的工作。
或者,您可以编写一个操作方法,该方法返回呈现为 XML 而不是 HTML 的视图。
像这样的东西:
Sounds like you want to create a REST API.
Have a look at Siesta which will do all the heavy lifting.
Alternatively you could write an action method which returns a view which renders as XML rather than HTML.
Something like:
如果您可以接受 JSON 结果,则以下操作应该可行:
这将为您提供相当基本的 JSON 查询结果。但是,如果您希望您的服务是可发现的 SOAP XML 服务等,那么设置另一个项目/网站来充当 Web 服务对我来说似乎是更好的主意。
If you could live with a JSON result, the following should work:
This would give you pretty a basic JSON query result. However, if you want your services to be discoverable SOAP XML services etc., setting up another project/website that acts as the web service would seem to be the better idea to me.
您可能可以在这里找到问题的答案:
请参阅从控制器的操作中返回 XML 作为 ActionResult?
You can probably find an answer to your question here:
See Return XML from a controller's action in as an ActionResult?