实现新方法后,我的api方法不会运行

时间:2014-04-04 22:42:44

标签: c# asp.net api

public class ContactsController : ApiController
{
    static readonly IContactsRepository repository = new ContactsRepository();
    //
    // GET: /Contacts/

    public IEnumerable<Contact> GetAllContacts()
    {
        return repository.GetAll();
    }

}

以上代码适用于API Call / api / contacts / GetAllContacts,并返回我的数据库中的联系人列表。我还想添加一个方法,使用/ api / contacts / getcontacts之类的东西返回特定的联系人?但是,一旦我添加以下代码:

public Contacts GetContact(int id)
{
    Contacts item = repository.Get(id);
    if (item == null)
    {
        throw new HttpResponseException(HttpStatusCode.NotFound);
    }
    return item;
}

我的原始电话(/ api / contacts / GetAllContact)将无效并显示以下错误:

"Message": "The request is invalid.",
"MessageDetail": "The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'ReservationsAPI.Models.Contacts GetContact(Int32)' in 'ReservationsAPI.Controllers.ContactsController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter."

编辑: route config

{
public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}
}

1 个答案:

答案 0 :(得分:1)

删除您手动创建的ContactS类并尝试此操作;

public class ContactController : ApiController
{
    static readonly IContactsRepository repository = new ContactsRepository();

    // GET api/Contact
    public IEnumerable<Contact> GetContact()
    {
        return repository.GetAll();
    }

    // GET api/Contact/5
    public IHttpActionResult GetContact(int id)
    {
        var contact = repository.Get(id);
        if (contact == null)
        {
            throw new HttpResponseException(HttpStatusCode.NotFound);
        }

        return contact;
    }

然后尝试调用这些网址;

/api/Contact
/api/Contact/1

使用此设置,您无需在路由中定义操作。