web api2 RESTful GET没有返回获取id

时间:2015-05-18 16:28:21

标签: asp.net-web-api asp.net-web-api-routing

不太确定我缺少什么

标准webapiconfig.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;

namespace MROVendorWebAPI
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}

非常基本的控制器

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using MROVendorWebAPI.Models;

namespace MROVendorWebAPI.Controllers
{
    public class VSMRICSController : ApiController
    {



        public IEnumerable<DB2VsmRicRecord> GetDB2VsmRicRecords()
        {
            string ErrorDescription = "";
            DB2VsmRicCollection myDB2VsmRicCollection = new DB2VsmRicCollection();
            if (myDB2VsmRicCollection.CreateCollection(ref ErrorDescription))
            {
                return myDB2VsmRicCollection.oDB2VsmRicList;
            }
            return null;
        }



        public DB2VsmRicRecord GetDB2VsmRicRecord(string ric)
        {
            string ErrorDescription = "";
            DB2VsmRicCollection myDB2VsmRicCollection = new DB2VsmRicCollection();
            if (myDB2VsmRicCollection.CreateCollection(ref ErrorDescription))
            {
                return myDB2VsmRicCollection.oDB2VsmRicList.FirstOrDefault(p => p.Ric == ric);
            }
            return null;
        }

    }
}

使用/ api / VSMRICS正常工作并返回整个集合 并使用/ api / VSMRICS?RIC = SAH正常工作并只返回一条记录,但/ api / VSMRICS / SAH返回整个集合。不确定为什么我需要在控制器中为这个方法添加某种路由?

2 个答案:

答案 0 :(得分:0)

duh从不介意它需要

public DB2VsmRicRecord GetDB2VsmRicRecord(string id)

答案 1 :(得分:0)

在传统路由中,它搜索路由中提到的RouteParameter作为id。

您也可以在此处更改路线:

config.Routes.MapHttpRoute(
   name: "DefaultApi",
   routeTemplate: "api/{controller}/{ric}",
   defaults: new { id = RouteParameter.Optional }
);

支持您的API:

public DB2VsmRicRecord GetDB2VsmRicRecord(string ric)
{
   string ErrorDescription = "";
   DB2VsmRicCollection myDB2VsmRicCollection = new DB2VsmRicCollection();
   if (myDB2VsmRicCollection.CreateCollection(ref ErrorDescription))
   {
      return myDB2VsmRicCollection.oDB2VsmRicList.FirstOrDefault(p => p.Ric == ric);
   }
   return null;
}