C# 引发HttpResponseException会导致未处理的异常
我正在学习Badrinarayanan Lakshmiraghavan的“实用ASP.NET Web API”教程 我认为这是在暗示可以使用一些异常将“404-notfound”类型的内容发送回浏览器。然而,我只是得到了常规程序“崩溃”(错误消息弹出) 我一定错过了什么。有人能告诉我可能是什么吗?(这里有很多类似的问题,但我找不到适合这个案例的问题) 我得到C# 引发HttpResponseException会导致未处理的异常,c#,asp.net-web-api,C#,Asp.net Web Api,我正在学习Badrinarayanan Lakshmiraghavan的“实用ASP.NET Web API”教程 我认为这是在暗示可以使用一些异常将“404-notfound”类型的内容发送回浏览器。然而,我只是得到了常规程序“崩溃”(错误消息弹出) 我一定错过了什么。有人能告诉我可能是什么吗?(这里有很多类似的问题,但我找不到适合这个案例的问题) 我得到 "HttpResponseException was unhandled by user code" 使用的URL http://loc
"HttpResponseException was unhandled by user code"
使用的URL
http://localhost:63694/api/employees/12344
代码
public class EmployeesController : ApiController
{
private static IList<Employee> list = new List<Employee>()
{
new Employee() {
Id = 12347, FirstName = "Joseph", LastName = "Law"}
};
// GET api/employees
public IEnumerable<Employee> Get()
{
return list;
}
// GET api/employees/12345
public Employee Get(int id)
{
var employee = list.FirstOrDefault(e => e.Id == id);
if (employee == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return employee;
}
}
公共类EmployeesController:ApicController
{
私有静态IList列表=新列表()
{
新雇员(){
Id=12347,FirstName=“约瑟夫”,LastName=“法律”}
};
//获取api/员工
公共IEnumerable Get()
{
退货清单;
}
//获取api/employees/12345
公共雇员获取(int id)
{
var employee=list.FirstOrDefault(e=>e.Id==Id);
if(employee==null)
{
抛出新的HttpResponseException(HttpStatusCode.NotFound);
}
返回员工;
}
}
WebApi应处理异常并返回异常中包含的状态代码。您可能不是在ApiController
派生的控制器中运行此命令,而是在从控制器
派生的控制器中运行此命令
您最好返回包含员工类型内容的HttpResponseMessage。在这种情况下,您可以更好地控制状态代码,如下所示:
var response = Request.CreateResponse(HttpStatusCode.Notfound);
return response
// GET api/employees/12345
public HttpResponseMessage Get(int id)
{
HttpResponseMessage response = null;
var employee = list.FirstOrDefault(e => e.Id == id);
if (employee == null)
{
response = new HttpResponseMessage(HttpStatusCode.NotFound);
}
else
{
response = Request.CreateResponse(HttpStatusCode.OK, employee);
}
return response;
}
实际上,你可以做其他两个用户发布的事情,但你的方式是正确的 Web API异常处理: 但是,如果您在VisualStudio中以调试模式运行,VS将警告您未处理的异常等。但是,如果不在调试模式下运行或部署到IIS,则该行为将正常工作,并将呈现404 not Found错误页面
Visual Studio试图检测并阻止所有未处理的异常,这只是在妨碍您的工作。您能否显示声明控制器类的整行内容。@G.Stoynev,您的意思是什么。所有控制器类都在上面。只缺少名称空间、使用和员工定义。你需要这些中的哪一个?我一定不知怎么错过了:-)在这种情况下-当异常到达管道末端时,应该将其转换为HttpMessage。嗨,我遇到了类似的问题,只是我的代码不包含在Web API控制器中。我创建了一个从
IHttpModule
继承的HttpModule。因此,Request.CreateResponse()
不可用。有人知道如何向客户端发送HttpResponseMessage(HttpStatusCode.Forbidden)
吗?谢谢,这似乎是一种更符合逻辑的方法-返回一些东西,而不是引发异常。为了一致性,我相信条件是(employee==null)应该像这样创建响应:response=Request.CreateErrorResponse(HttpStatusCode.NotFound,“未找到员工”);谢谢,我尝试将其设置为“发布”模式,但仍然出现错误。您正在启动调试器(F5/播放按钮)还是只是编译和访问您的站点?您是否尝试部署到IIS?