为什么返回xml而不是值?

时间:2014-05-29 06:06:02

标签: asp.net-mvc-4

如何将样式信息添加到从我的Web服务返回的xml中?

示例:

public class ServiceController : ApiController
    {
        // GET api/service
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/service/5
        public string Get(int id)
        {
            return "value";
        }

        // POST api/service
        public void Post([FromBody]string value)
        {
        }

        // PUT api/service/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/service/5
        public void Delete(int id)
        {
        }
    }

此XML文件似乎没有与之关联的任何样式信息。文档树如下所示。

<ArrayOfstring><string>value1</string><string>value2</string></ArrayOfstring>

我正在使用网址: HTTP:/ API /服务

为什么要返回xml文件?

1 个答案:

答案 0 :(得分:0)

这是因为当您在浏览器中键入http:/ api / Service时,Web api会对http动词起作用,您将调用的第一个方法是Get返回IEnumerable字符串,这就是它返回它的原因。

如果你想返回单个值,那么写下这样的东西。

    public string Get()
    {
        return "Value";
    }

你还推出了另一个get的实现,它将返回单个字符串值。但为此你需要在URL中传递参数。

与http:/ api / Service / 5类似,它将调用您的Get(int id)方法。

相关问题