我真的需要一些帮助。
我正在编写一个小型WebApi程序。
虽然单位测试我注意到我无法向我的帖子方法发送元素列表。
首先来看看我的单元测试:
[TestMethod]
public async Task PostWithExpandoObjectSerilasationToDataType()
{
//Define an imaginary Car Object
List<dynamic> listExpando = new List<dynamic>();
dynamic obj1 = new ExpandoObject();
obj1.Attribute = "PS";
obj1.DataType = "Integer";
obj1.EntityId = "3";
obj1.DefaultValue = "";
dynamic obj2 = new ExpandoObject();
obj2.Attribute = "Color";
obj2.DataType = "Text Only";
obj2.EntityId = "3";
obj2.DefaultValue = "";
dynamic obj3 = new ExpandoObject();
obj3.Attribute = "Km";
obj3.DataType = "Number";
obj3.EntityId = "3";
obj3.DefaultValue = "1.3";
listExpando.Add(obj1);
listExpando.Add(obj2);
listExpando.Add(obj3);
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
javaScriptSerializer.RegisterConverters(new JavaScriptConverter[] { new ExpandoJsonconverter() });
string jsonOfTest = javaScriptSerializer.Serialize(listExpando);
// arrange
UnityContainer container = UnityConfig.RegisterComponents();
var start = new Startup(container);
using (TestServer server = TestServer.Create(builder => start.Configuration(builder)))
{
using (var client = new HttpClient(server.Handler))
{
HttpContent content = new StringContent(jsonOfTest, Encoding.UTF8, "application/json");
var request = new HttpRequestMessage
{
RequestUri = new Uri("http://testserver/odata/Attributes"),
Method = HttpMethod.Post,
Content = content
};
string jsonContent = content.ReadAsStringAsync().Result;
request.Headers.Add("Prefer", "return=representation");
// act
HttpResponseMessage response = await client.SendAsync(request);
Attributes result = response.Content.ReadAsAsync<Attributes>().Result;
// assert
Assert.IsNotNull(response);
Assert.AreEqual(HttpStatusCode.Created, response.StatusCode);
Assert.IsNotNull(result, "No result content found");
Assert.IsNotNull(result.Attribute);
}
}
}
接下来是我的帖子方法:
public IHttpActionResult Post([ModelBinder]IEnumerable<Attributes> att)
{....}
说到Post方法 att总是空的
尝试使用Rest服务时,我收到以下消息:
“message”:“Collection(EAVService.Entities.Attributes)不是实体类型。仅支持实体类型。”
谷歌搜索并尝试了不同的东西,但我没有找到一个有效的解决方案
有谁可以帮助我解决我的问题? :)
最诚挚的问候 安德烈
答案 0 :(得分:2)
在OData中,POST通常用于add a single entity to a collection。因此,您的Post
方法应具有以下签名:
public IHttpActionResult Post(Attributes att)
参见&#34;向实体集添加实体&#34;在Create an OData v4 Endpoint Using ASP.NET Web API 2.2中获取完整示例。
如果您需要在单个服务调用中创建多个Attributes
实体,则有两种选择:
在您的服务中实施batch request处理
实施接受Attributes
个实体集合的OData action,并将其批量添加到相应的实体集