GET 方法返回空

GET method returning empty

晚安,我正在开发一个 WebApi,我正在使用代码优先方法,为此我使用了 entity framework 6.0.1,在我的项目中我有以下 classes PersonController.cs、Configurations.cs(我现在手动插入数据)和我的 Person class,我正在使用 Postman 来模拟请求,我在此处查找了一些示例网站但是none相当于我的,如果有人能帮助我谢谢。

PersonController.cs

using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebApi.Models;
using WebApi.Contexto;

namespace WebApi.Controllers
{
    public class PersonController : ApiController
    {
        private readonly Context contexto = new Context();
        [Route("api/person")]
        [HttpGet]
        public IHttpActionResult getAll(string search)
        {
            if (string.IsNullOrEmpty(search))
            {
                search = "";
            }
            var list = contexto.People.Where(x => x.firstName.Contains(search) || x.lastName.Contains(search));

            return Ok(list);

        } 
     }
}

Configurations.cs

namespace WebApi.Migrations
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Migrations;
    using System.Linq;
    using WebApi.Models;

    internal sealed class Configuration : DbMigrationsConfiguration<WebApi.Contexto.Context>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = false;
        }

        protected override void Seed(WebApi.Contexto.Context context)
        {
            //  This method will be called after migrating to the latest version.

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method 
            //  to avoid creating duplicate seed data. E.g.

            context.People.Add(new Person { firstName = "Andrew ", lastName = "Teste", id = 1, birthDate = new DateTime(2021, 01, 31) });
           
        }
    }
}

Person.cs

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

namespace WebApi.Models
{
    public class Person
    {
        public int id { get; set; }
        public string firstName { get; set; }
        public string lastName { get; set; }
        public DateTime birthDate { get; set; }
    }
}

您缺少 [HttpGet] 属性中的参数,因此您的方法参数实际上并未获取您的查询字符串。

尝试

[HttpGet("{search}")]

public IHttpActionResult GetAll([FromQuery] string search)

调用 api

时搜索参数为空

一轮的工作是创建一个简单的模型或class 喜欢

public class Query
{
   public string Search {get;set;}
}

并将您的方法更改为

public IHttpActionResult getAll([FromBody]Query query)
{
        var search = query.Search;

        if (string.IsNullOrEmpty(search))
        {
            search = "";
        }

        var list = contexto.People.Where(x => x.firstName.Contains(search) || 
        x.lastName.Contains(search));

        return Ok(list);

} 

您的 Postman 负载应该像

{
   "search":"a"
}

特此通知您,我的错误是在数据库连接字符串中发现的,它没有参数:

Integrated Security = True;

感谢大家的帮助