use*_*331 5 c# sql-server asp.net asp.net-web-api
我正在使用ASP.NET Web API,当我运行此方法时,我收到此错误发生了错误.
public List<DeviceClass> CheckDevice(string device)
{
devices = new List<DeviceClass>();
using( connection = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand("uspCheckDeviceID", connection))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("@sp", SqlDbType.VarChar).Value = device;
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
if(reader.HasRows)
{
if(reader.Read())
{
DeviceClass model = new DeviceClass();
model.DeviceId = reader.GetValue(0).ToString();
model.Name = reader.GetValue(1).ToString();
model.Owner = reader.GetValue(2).ToString();
devices.Add(model);
}
}
connection.Close();
}
}
}
return devices;
}
Run Code Online (Sandbox Code Playgroud)
我想确定它的代码或服务器连接是什么.
这是我得到一个例子的存储过程:
declare @sp varchar(30)
set @sp ='marksiphoneid'
exec uspCheckDeviceID @sp
Run Code Online (Sandbox Code Playgroud)
我尝试从存储过程中获取结果的方式有问题吗?
错误是
无法加载资源:服务器响应状态为500(内部服务器错误)
把你的方法变成这样:
public HttpResponseMessage CheckDevice(string device)
{
try
{
devices = new List<DeviceClass>();
using (connection = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand("uspCheckDeviceID", connection))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("@sp", SqlDbType.VarChar).Value = device;
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.HasRows)
{
if (reader.Read())
{
DeviceClass model = new DeviceClass();
model.DeviceId = reader.GetValue(0).ToString();
model.Name = reader.GetValue(1).ToString();
model.Owner = reader.GetValue(2).ToString();
devices.Add(model);
}
}
connection.Close();
}
}
}
return Request.CreateResponse(HttpStatusCode.OK,
devices.ToList());
}
catch (Exception e)
{
//Request.CreateErrorResponse can do the same thing
var err = new HttpRequestMessage().
CreateErrorResponse(HttpStatusCode.InternalServerError,
e.ToString());
return new HttpResponseException(err);
}
}
Run Code Online (Sandbox Code Playgroud)
然后,当错误发生时,您可以获取 Exception ToString。
为了确保您可以看到异常消息,您可以使用Fiddler或PostMan来测试您的 API。
。
此外,我只是尝试OP的问题评论中的方式,
就我而言,我正在测试返回一些我自己定义的异常对象,
最初当我通过输入 url 到 Google Chrome 调用 GET 方法时,
Chrome 只给我一条毫无意义的消息An error has occured,
在我添加之后
GlobalConfiguration.Configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
Run Code Online (Sandbox Code Playgroud)
在Global.asax.cs该方法中protected void Application_Start(),
我的异常对象显示正确。
。
一个小时后,我发现它也可以在WebApiConfig.cs方法中public static void Register(HttpConfiguration config)完成
config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5514 次 |
| 最近记录: |