![](/img/trans.png)
[英]ASP.NET Web API - test error : an error has occurred - how to fix it?
[英]ASP.NET Web API An error has occurred
我正在使用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;
}
我想确定它的代码或服务器连接是什么。
这是我得到一个例子的存储过程:
declare @sp varchar(30)
set @sp ='marksiphoneid'
exec uspCheckDeviceID @sp
我尝试从存储过程中获取结果的方式有问题吗?
错误是
无法加载资源:服务器响应状态为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);
}
}
然后,当错误发生时,您可以获取Exception ToString。
要确保您可以看到异常消息,您可以使用Fiddler
或PostMan
来测试您的API。
。
此外,我只是在OP的问题评论中试试方式,
在我的情况下,我正在测试返回自己定义的一些异常对象,
最初我打电话给GET方法时输入url到Google Chrome,
Chrome只是给我一个毫无意义的meesage An error has occured
,
在我添加之后
GlobalConfiguration.Configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
在Global.asax.cs
中的方法protected void Application_Start()
,
我的异常对象显示正确。
。
一小时后我发现它也可以在方法public static void Register(HttpConfiguration config)
中的WebApiConfig.cs
中完成。
config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
您500错误表示您的服务出现内部错误。 它可能是里面的一切。
例如,您的reader.GetValue(1)返回null。 因此,您将出现null错误,您的服务器将返回500。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.