我的WebApiConfig:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
ODataModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<Applicant>("Applicants");
builder.EntitySet<Country>("Countries");
builder.EntitySet<Program>("Programs");
builder.EntitySet<Campus>("Campuses");
builder.EntitySet<AcademicYear>("AcademicYears");
builder.EntitySet<Citizenship>("Citizenships");
builder.EntitySet<ProgramChoice>("ProgramChoices");
builder.EntitySet<Application>("Applications");
builder.EntitySet<ProvinceState>("States");
config.MapODataServiceRoute(
routeName: "ODataRoute",
routePrefix: null,
model: builder.GetEdmModel());
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{key}",
defaults: new { key = RouteParameter.Optional }
);
}
}
我的控制器获取方法返回项目列表:
[EnableQuery]
public IQueryable<ProvinceState> Get()
{
return db.ProvinceStates;
}
我的控制器获取方法返回单个项目:
[EnableQuery]
public SingleResult<ProvinceState> Get([FromODataUri] string key)
{
IQueryable<ProvinceState> result = db.ProvinceStates.Where(c => c.ProvinceStateCode == key);
return SingleResult.Create(result);
}
问题如下:
HTTP错误404.0 - 未找到
调试时,在向get方法发出返回单个项目的请求时,调试器不会触及单个项目GET的断点。但它在请求List GET方法时会这样做。
任何建议或帮助都会非常感谢,提前谢谢。
答案 0 :(得分:5)
由于您有一个由ProvinceStateCode
和CountryCode
组成的复合键,因此您需要修改Get
方法以接受这两个值。
[HttpGet]
[ODataRoute("States(ProvinceStateCode={stateCode},CountryCode={countryCode})")]
[EnableQuery]
public IHttpActionResult Get([FromODataUri] string stateCode, [FromODataUri] string countryCode)
{
var result = db.ProvinceStates.FirstOrDefault(c => c.ProvinceStateCode == stateCode && c.CountryCode == countryCode);
if (result == null)
{
return NotFound();
}
else
{
return Ok(result);
}
}
然后按如下方式检索各个州:
GET http://host/States(ProvinceStateCode='AL',CountryCode='US')