如何在ASP.NET MVC中拥有"服务"页面?

Sha*_*ica 1 c# model-view-controller asp.net-mvc visual-studio-2010

MVC新手在这里:

我或多或少地研究了MVC的页面导航方面.但是,假设我不想导航到View,而是希望从网站上获得响应,例如通过向http://mysite.com/Services/GetFoo/123发送请求我想要发出数据库请求以选择FooID为123 的对象,并将其序列化为XML.

你是怎样做的?

Dar*_*rov 7

我会写一个自定义动作结果:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在我的控制器中:

public ActionResult GetFoo(int id)
{
    FooModel foo = _repository.GetFoo(id);
    return new XmlResult(foo);
}
Run Code Online (Sandbox Code Playgroud)

如果这return new XmlResult(foo);对你的眼睛感到难看,你可以有一个扩展方法:

public static class ControllersExtension
{
    public static ActionResult Xml(this ControllerBase controller, object data)
    {
        return new XmlResult(data);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后:

public ActionResult GetFoo(int id)
{
    FooModel foo = _repository.GetFoo(id);
    return this.Xml(foo);
}
Run Code Online (Sandbox Code Playgroud)