MVC3 Action as a simple web service

2019-06-25 10:29发布

问题:

How could I use this action as a service?

 public class HomeController : Controller {

     public string GetSomeValue(){
         return "This is some value";
     }
 }

If I navigate to this URL, http://mysite.com/Home/GetSomeValue, it returns a string, without any html or markup of any kind.

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?

And if this is possible, how would I do this (Say from the code behind of another asp.net web site)?

Thanks in advance.

回答1:

100% Nothing wrong with doing this.

A sample application - NerdDinner - does this very same thing to load dinners restfully.

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 )

e.g.

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");
}


回答2:

This is essentially a RESTful service:

http://www.ibm.com/developerworks/webservices/library/ws-restful/

All you gonna need is to construct the http request to consume this service, you could use Hammock to construct such requests:

https://github.com/danielcrenna/hammock