从WebAPI获取所有内容

时间:2015-06-08 15:56:34

标签: c# asp.net-web-api

对不起我的错误解释,如果是这样的话。

我有一个WebAPI,我需要返回我数据库中的所有艺术家。

我的代码如下:

ArtistRepository.cs:

public class ArtistRepository: IDisposable
{
    private WhereIsMyBandContext context;

    public ArtistRepository(WhereIsMyBandContext context)
    {
        this.context = context;
    }

    public IEnumerable<Artist> GetAllArtists()
    {
        return context.Artists.ToList();
    }

    private bool disposed = false;

    protected virtual void Dispose(bool disposing)
    {
        if (!this.disposed)
        {
            if (disposing)
            {
                context.Dispose();
            }
        }
        this.disposed = true;
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
}

ArtistController.cs:

public class ArtistsController : ApiController
{
    public ArtistRepository repository = new ArtistRepository(new WhereIsMyBandContext());

    [HttpGet]
    public IEnumerable<Artist> Get()
    {
        return repository.GetAllArtists();
    }
}

Program.cs:(我的切入点

class Program
{
    static void Main(string[] args)
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("http://localhost:57026/");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            WebClient webClient = new WebClient();

            var response = webClient.DownloadString("http://localhost:57026/api/Artists");
            Console.WriteLine(response);
            Console.ReadLine();
        }
    }
}

我得到的回报总是这样:[]并填充我的数据库。 谢谢你的帮助。

0 个答案:

没有答案
相关问题