【发布时间】:2014-09-12 12:56:13
【问题描述】:
我是 ASP.net(Visual Studio 2010,.NET 3.5)的新手,我想做以下事情:
我正在使用 OperationContracts 以 JSON 形式提供 Web 服务数据。一个用 angularJS 编写的移动应用正在使用这些 JSON 响应。
我希望每个 OperationContract 响应都是由标准响应对象包装的相关数据对象。
例如:
{
error: false,
error_detail: '',
authenticated: false,
data: { }
}
在数据变量中将包含每个请求类型所需的任何内容。
移动应用程序检查相关变量,如果一切正常,则将数据传递给任何请求它的对象(这部分正在工作并准备就绪)。
我知道它经常不受欢迎,但我希望基本上返回一个匿名对象,因为我可以轻松地构造一个匿名对象和我需要的任何数据,但似乎我被强行拒绝了这样做的能力。理想情况下,我不想在移动应用端添加另一层反序列化或其他东西,我希望在客户端做尽可能少的处理。
我可以很容易地使用我自己的测试 Web API 项目(请参阅下面的示例控制器)使其按要求工作,但不幸的是,我正在添加到现有项目中,而不是开始新项目。
谁能给点建议?
Web API 代码示例
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace tut3.Controllers
{
public class ValuesController : ApiController
{
/**
* Take the provided dataResponse object and embed it into
* the data variable of the default response object
**/
private object Response(object dataResponse)
{
return new
{
success = false,
error = "",
error_detail = "",
authenticated = false,
token = "",
token_expiry = 0,
data = dataResponse
};
}
/**
* This could be a normal web service that uses the Knadel database etc etc, the only difference is
* the return is sent through the Response() function
**/
public object Get()
{
object[] local = new[] {
new { cat = "cat", dog = "dog" },
new { cat = "cat", dog = "dog" },
new { cat = "cat", dog = "dog" },
new { cat = "cat", dog = "dog" },
new { cat = "cat", dog = "dog" }
};
/**
* Pass local to Response(), embed it in data and then return the whole thing
**/
return Response(local);
}
}
}
【问题讨论】: