C#WebApi控制器(状态控制器目前有2个Get方法,1个返回List,第二个返回Single Item)

我的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);
}

问题如下:

>当我请求LocalHost:### / States时,Get方法正确返回状态列表而没有任何问题.
>但是当我请求LocalHost:### / States(‘AL’)时,为了获得特定项目,我收到以下错误.

HTTP错误404.0 – 未找到

您要查找的资源已被删除,名称已更改或暂时不可用.

在调试时,并且在向返回单个项的get方法发出请求时,调试器不会达到单项GET的断点.但它在请求List GET方法时会这样做.

任何建议或帮助将非常感谢,提前感谢.

解决方法:

由于您具有由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')
上一篇:c# – 异常消息是On数据上下文类型,有一个*的IQueryable属性,其元素类型不是实体类型


下一篇:c# – 如何调用OData客户端生成器生成的OData函数/操作?