使用当前方法,我无法从以下查询字符串中获得正确的结果: / API /数据名称= STORM%202006-1%20A2&安培;价格类型= CVR
[HttpGet]
public IEnumerable<database_WICs> Get([FromUri] Query query)
{
var data = from c in db.database_WICs
where c.Name == query.name ||
c.CUSIP == query.cusip ||
c.ISINs == query.isin ||
c.Cover == query.price_type
select c;
return data.ToList();
}
使用linq查询是否有更好的方法来实现此过滤器。如果是这样,任何例子将非常感谢。
答案 0 :(得分:0)
我想你有一个名为Query的模型和一个名为Data的API控制器,如下所示:
public class Query
{
public string name { get; set; }
public string cusip { get; set; }
public string isin { get; set; }
public string price_type { get; set; }
}
public class DataController : ApiController
{
//GET api/Data
public IEnumerable<database_WICs> Get([FromUri] Query query)
{
var data = from c in db.database_WICs
where c.Name == query.name ||
c.CUSIP == query.cusip ||
c.ISINs == query.isin ||
c.Cover == query.price_type
select c;
return data;
}
}
您的API GET方法很好,只需删除“toList()”即可。如果您希望它返回HttpResponseMessage,您可以更改它,如下所示:
//GET api/Data
public HttpResponseMessage Get([FromUri] Query query)
{
var data = from c in db.database_WICs
where c.Name == query.name ||
c.CUSIP == query.cusip ||
c.ISINs == query.isin ||
c.Cover == query.price_type
select c;
if (!data.Any())
{
var message = string.Format("No database_WICs was found");
return Request.CreateErrorResponse(HttpStatusCode.NotFound, message);
}
return Request.CreateResponse(HttpStatusCode.OK, data);
}
但问题是你的URI错了。 URI应如下所示:
/api/Data/?name=STORM&cusip=20&isin=2006-1%20A2&price_type=cvr
如果您通过AJAX调用将JSON对象传递给Web API,则AJAX调用应如下所示:
var data = {name:"STORM",cusip:"20",isin:"2006-1 20A2",price_type:"cvr"} ;
$.ajax({
url: "/api/Data/",
type: 'GET',
contentType: 'application/json',
data: JSON.stringify(data)
});
答案 1 :(得分:0)
我设法使用上面的Lin解决方案提出了搜索名称和价格类型等参数的解决方案:
public HttpResponseMessage Get([FromUri] Query query)
{
var data = db.database_Dwic.AsQueryable();
if (query.name != null)
{
data = data.Where(c => c.Name.Trim() == query.name);
}
if (query.price_type != null)
{
data = data.Where(c => c.Cover == query.price_type);
}
if (!data.Any())
{
var message = string.Format("No data was found");
return Request.CreateErrorResponse(HttpStatusCode.NotFound, message);
}
return Request.CreateResponse(HttpStatusCode.OK, data);
}