C# - Swagger插入值并将字符串数组传递给Linq显示NULL而不是插入的值
问题描述:
在Swagger中插入一些值,我想将包含这些值的字符串数组传递给Linq。 (在这种情况下,ID是字符串)。如果我传递一个简单的字符串,而不是一个数组,它可以插入一个值。但我需要传递一组值。C# - Swagger插入值并将字符串数组传递给Linq显示NULL而不是插入的值
这里是由试图插入2个值当API建立了一个链接(它看起来怪异的数组):http://localhost:port/api/Members?ids=97882831302&ids=97882831308
的问题是,该阵列显示NULL,而不是插入的值。我得到以下错误:
"ExceptionMessage": "Unable to create a null constant value of type 'System.String[]'. Only entity types, enumeration types or primitive types are supported in this context."
public class MembersController : ApiController
{
public HttpResponseMessage GetAllMembersByIdentifiers(string[] ids) {
using (sampleEntities entities = new sampleEntities()){
var numbers = entities.tblmembers
.Where(p => ids.Contains(p.identify) ).ToList();
if (numbers != null)
{
return Request.CreateResponse(HttpStatusCode.OK, numbers);
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Member with id: " + ids + " not found");
}
}
}
}
答
Ø认为你已经在你的代码2个问题..
FIRST:
用,像通数据:
98989794, //<---
4343545345
第二:
在C#我可以建议您检查字符串null或空,如:
public class MembersController : ApiController
{
[HttpGet]
[Route("api/Members/Find/{ids}")]
public HttpResponseMessage FindMemebers([FromUri]string[] ids) {
// CHECK THE ARRAY NOT EMPTY
if(!ids.Any() || ids.All(xx=> string.isNullOrEmpty(xx)) return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "empty params");
using (sampleEntities entities = new sampleEntities()){
var numbers = entities.tblmembers
.Where(p => ids.Contains(p.identify) ).ToList();
if (numbers != null)
{
return Request.CreateResponse(HttpStatusCode.OK, numbers);
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Member with id: " + ids + " not found");
}
}
}
}
答
什么解决的是:
加入
[FromUri]
通过@ federico-暗示scamuzzi将
string[]
替换为List<string>
。
所以在代码如下所示:
public HttpResponseMessage FindMemebers([FromUri]List<string> ids) { ...
似乎有一个“),”缺少在首届“如果”行。它也说“BadRequest()”不起作用(它说它不能转换成HttpResponse)。我用“CreateErrorResponse”取代了它。我也尝试在Swagger中用逗号“,”插入值(没有在Swagger中说插入每行的值 - 没有提及逗号)。我仍然收到一个错误:“ExceptionMessage”:“值不能为空。\ r \ nParameter name:source”, “ExceptionType”:“System.ArgumentNullException”' – adlisval
对不起......只是尝试调用你的方法GET (或者放一个[Route]装饰)和[HttpGet]动词装饰)...并尝试设置([FromUri] string [] ids)因为我认为它现在是QUERYSTRING PARAMS的方面 –
可以请你分享代码怎么做?我试过'[Route] [HttpGet] public HttpResponseMessage GetAllMembersByIdentifiers(string [] ids){...'。 'BadRequest()'仍然用红色加下划线。我不知道你的意思是什么“调用你的方法GET”...如果它重新命名为GET,我尝试和'BadRequest()'仍然加下划线。 – adlisval