【发布时间】:2019-02-02 10:23:06
【问题描述】:
我不知道从哪里开始。我之前问过一个问题,有人建议我看看属性路由。我阅读了它,虽然它帮助我创建了下面的代码,但我仍然不确定如何像我想要的那样限制它。
public class ReviewController : ApiController
{
private Review db = new Review();
////This GET works. It was auto-generated by Visual Studio.
// GET: api/Review
public IQueryable<Review> GetReview()
{
return db.Review;
}
////This is the GET that I'm trying to write, but don't know what to do
// GET: api
[Route("api/review/site")]
[HttpGet]
public IEnumerable<Review> FindStoreBySite(int SiteID)
{
return db.Review
}
////This GET also works and was generated by VS.
// GET: api/Review/5
[ResponseType(typeof(Review))]
public IHttpActionResult GetReview(int id)
{
Review review = db.Review.Find(id);
if (review == null)
{
return NotFound();
}
return Ok(review);
}
基本上,我的目标是将 API 返回的内容限制为仅SiteID 等于传递到 URL 中的任何值的结果。我什至不知道从哪里开始,并且谷歌搜索/搜索堆栈溢出以获取“在 web api 中放入什么返回”一直没有结果。
如何根据 ReviewID 以外的参数告诉 API 我想要返回什么?
编辑:我已根据以下答案中的建议更新了代码,但现在我遇到了一个新错误。
这是当前代码:
private ReviewAPIModel db = new ReviewAPIModel();
// GET: api/Review
[Route("api/Review")]
[HttpGet]
public IQueryable<Review> GetReview()
{
return db.Review;
}
// GET: api
[Route("api/Review/site/{siteid}")]
[HttpGet]
public IEnumerable<Review> FindStoreBySite(int siteid)
{
return db.Review.Where(Review => Review.SiteID == siteid);
}
// GET: api/Review/5
[ResponseType(typeof(Review))]
public IHttpActionResult GetReview(int id)
{
Review review = db.Review.Find(id);
if (review == null)
{
return NotFound();
}
return Ok(review);
}
}
这是我得到的错误:
Multiple actions were found that match the request
当我用谷歌搜索它时,我会想到这个问题:Multiple actions were found that match the request in Web Api
但是,我已经尝试了那里的答案(我已经确认我使用的是 Web API V2,并且我的 webapiconfig.cs 文件包含 config.MapHttpAttributeRoutes(); 行。
此外,正如您在上面的代码中看到的,我已经包含了适当的路由。但是,我仍然收到一条错误消息,告诉我它返回了两个冲突的 API 调用。
【问题讨论】:
标签: c# asp.net-web-api