问题描述
我怎么能使用此操作作为一种服务?
How could I use this action as a service?
public class HomeController : Controller {
public string GetSomeValue(){
return "This is some value";
}
}
如果我浏览到这个网址,,它返回一个字符串,没有任何形式的任何HTML或标记。
If I navigate to this URL, http://mysite.com/Home/GetSomeValue, it returns a string, without any html or markup of any kind.
那么,是什么让我使用此方法作为返回有意义的服务,比如JSON,我可以从任何地方打电话?
So, what is to keep me from using this method as a service that returned something meaningful, say json, that I could call from anywhere?
如果这是可能的,我会怎么做(说从另一个asp.net网站背后的code)?
And if this is possible, how would I do this (Say from the code behind of another asp.net web site)?
先谢谢了。
推荐答案
100%的没有错,这样做。
100% Nothing wrong with doing this.
一个示例应用程序 - 的NerdDinner - 这是否同样的事情以REST风格加载晚餐
A sample application - NerdDinner - does this very same thing to load dinners restfully.
请参阅控制器和的以JavaScript文件(寻找NerdDinner.FindMostPopularDinners)
See http://nerddinner.codeplex.com/SourceControl/changeset/view/70027#874260 for controller and http://nerddinner.codeplex.com/SourceControl/changeset/view/70027#874293 for javascript file ( look for NerdDinner.FindMostPopularDinners )
例如
C#
// AJAX: /Search/GetMostPopularDinners
// AJAX: /Search/GetMostPopularDinners?limit=5
[HttpPost]
public ActionResult GetMostPopularDinners(int? limit)
{
var dinners = dinnerRepository.FindUpcomingDinners();
// Default the limit to 40, if not supplied.
if (!limit.HasValue)
limit = 40;
var mostPopularDinners = from dinner in dinners
orderby dinner.RSVPs.Count descending
select dinner;
var jsonDinners =
mostPopularDinners.Take(limit.Value).AsEnumerable()
.Select(item => JsonDinnerFromDinner(item));
return Json(jsonDinners.ToList());
}
JS
NerdDinner.FindMostPopularDinners = function (limit) {
$.post("/Search/GetMostPopularDinners", { "limit": limit }, NerdDinner._renderDinners, "json");
}
这篇关于MVC3行动作为一个简单的Web服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!