带有dotnet核心的REST API

时间:2018-05-01 18:56:11

标签: c# json asp.net-core

感谢您的观察,我确实使用以下代码应用了它们但是在测试之后api没有返回任何数据。我甚至没有使用我的连接字符串而不是dbcontext!我收到此错误当读取器关闭且我的阅读器打开时,无效尝试调用FieldCount。我现在处于这种情况一周有任何帮助。 FromSql查询只返回单个表的实体。我的Store过程接受一个参数并与4个表连接。我已尝试使用“ExecuteSqlCommand”查询,因为结果是-1我得到。

using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using ActivaMobileAgent.Persistence;
using Microsoft.EntityFrameworkCore;
using ActivaMobileAgent.Model;
using System.Linq;
using System.Collections.Generic;
using System.Data.SqlClient;
using System;
using Dapper;
using System.Data;
using System.Data.Common;

 namespace ActivaMobileAgent.Controllers
{
    [Route("/api/Policy")]
    public class PolicyController : Controller
    {
    private readonly ActivaMobileAgentDbContext context;

    public PolicyController(ActivaMobileAgentDbContext context) => this.context = context;

    public readonly string connectionString = "Data Source=Localhost;Initial Catalog=HELLOxx;User=sa; Password=Helloxx";

    [HttpGet("{id}")]

    public async Task<IActionResult> GetPolicy(string id)
    {
        using (var connection = new SqlConnection("Data Source=Localhost;Initial Catalog=Helios;User=sa; Password=P@ssw0rd"))
        {
            SqlCommand command = new SqlCommand();
            command.Connection = connection;
            command.CommandType = System.Data.CommandType.StoredProcedure;
            command.CommandText ="dbo.sproc_Contract_Get";
            command.Parameters.Add(new SqlParameter("@ContractNumber", SqlDbType.VarChar) { Value = id });
            connection.Open();
            using (var result = await command.ExecuteReaderAsync())
            {
                return Json(result);
            }
        }
    }

}

}

2 个答案:

答案 0 :(得分:0)

您的网络方法不会返回任何数据。

不要让方法返回任何内容,而是将方法签名修改为

public async Task<IActionResult> GetPolicy( int id )

完成后,编译器会期望此方法返回一些数据。 我想存储的proc会返回一些数据,所以你必须把它放在某个地方。之后,您可以使用

返回值
return Ok(thedata);

例如,检查Ok方法。 如果出现问题,你不应该返回Ok offcourse,而是另一个Http状态代码,表明出了什么问题。

这让我想说REST服务中的函数应该总是返回正确的HTTP状态代码。因此,所有REST方法都应该返回IActionResult或Task,而不仅仅是返回的数据

编辑问题后编辑

ExecuteReader()方法返回一个实现IDataReader的类。将datareader返回给您的Web服务的使用者显然是不正确的。 相反,您必须使用IDataReader读取数据并使用该数据填充某种模型,您可以使用该模型返回给您的服务使用者。

List<SomeClass> result = new List<SomeClass>();

using (var reader = await command.ExecuteReaderAsync())
{
    while( reader.Read() )
    {
        result.Add(new SomeClass(dr.GetInt32(0), dr.GetString(1));
    }
}

return Ok(result);

接下来,我建议你不要自己将数据格式化为json或xml或其他任何东西。让ASP.NET为您处理。 ASP.NET将根据已收到的请求的值accept-header将结果序列化为适当的格式。

答案 1 :(得分:0)

ExecuteReaderAsync返回Task<SqlDataReader>。这可能不是序列化为JSON结果的有用类型。它表示数据集上的光标,而不是数据本身;数据尚未实际从数据库中恢复。正如this blog article所解释的那样,没有一种将SqlDataReader转换为JSON的内置方法。这里提到了几种方法,但需要注意的是,您必须编写迭代SqlDataReader并从中构造结果的代码。

通常,为了让这项工作更轻松,您可以使用Object-Relational Mapper为您完成此项工作,例如Dapper,它支持存储过程(免责声明:我从未使用过小巧玲珑)。 Entity Framework是.net应用程序的常用程序,因为它是由Microsoft构建的,但它非常繁重,使用起来很复杂。

编辑:哦 - 我没有发现你已经有了Entity Framework DbContext。这应该允许您执行存储过程并将其原生映射到结果。