MVC3 action as a simple web service

How can I use this action as a service?

public class HomeController : Controller { public string GetSomeValue(){ return "This is some value"; } } 

If I go to this URL, http://mysite.com/Home/GetSomeValue , it will return the string without any html or markup of any type.

So, what prevents me from using this method as a service that returns something meaningful, like json, which I could call from anywhere?

And if it is possible, how would I do it (tell me from the code behind another asp.net website)?

Thanks in advance.

+4
source share
2 answers

100% There is nothing wrong with that.

An example application, NerdDinner, does the same thing as when loading lunches.

See http://nerddinner.codeplex.com/SourceControl/changeset/view/70027#874260 for the controller and http://nerddinner.codeplex.com/SourceControl/changeset/view/70027#874293 for the javascript file (find NerdDinner.FindMostPopularDinners )

eg.

FROM#

  // 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"); } 
+4
source

This is essentially a RESTful service:

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

All you need to do is build an HTTP request to use this service, you can use Hammock to create these requests:

https://github.com/danielcrenna/hammock

+2
source

Source: https://habr.com/ru/post/1396277/


All Articles