How to have "service" pages in ASP.NET MVC?
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 we开发者_C百科b 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?
I would write a custom action result:
public class XmlResult : ActionResult
{
private readonly object _data;
public XmlResult(object data)
{
if (data == null)
{
throw new ArgumentNullException("data");
}
_data = data;
}
public override void ExecuteResult(ControllerContext context)
{
// You could use any XML serializer that fits your needs
// In this example I use XmlSerializer
var serializer = new XmlSerializer(_data.GetType());
var response = context.HttpContext.Response;
response.ContentType = "text/xml";
serializer.Serialize(response.OutputStream, _data);
}
}
and then in my controller:
public ActionResult GetFoo(int id)
{
FooModel foo = _repository.GetFoo(id);
return new XmlResult(foo);
}
And if this return new XmlResult(foo);
feels ugly to your eyes, you could have an extension method:
public static class ControllersExtension
{
public static ActionResult Xml(this ControllerBase controller, object data)
{
return new XmlResult(data);
}
}
and then:
public ActionResult GetFoo(int id)
{
FooModel foo = _repository.GetFoo(id);
return this.Xml(foo);
}
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:
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<MyModel>" ContentType="text/xml" %>
<%= SerializationHelper.SerializeAsXml(Model) %>
If you could live with a JSON result, the following should work:
public class ServicesController : Controller
{
public ActionResult GetFoo(int id)
{
var dbResult = SomeDbUtil.GetFoo(id);
return this.Json(dbResult);
}
}
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.
You can probably find an answer to your question here:
See Return XML from a controller's action in as an ActionResult?
精彩评论