提问人:springathing 提问时间:9/14/2018 最后编辑:jonscaspringathing 更新时间:9/14/2018 访问量:1724
为什么我在“HttpException”的 Web API 项目中收到缺少命名空间错误
Why am I getting a missing namespace error in my Web API project for 'HttpException'
问:
在 ASP.NET Web Api 2 Building a REST Service from Start to Finish 一书之后,我遇到了一个命名空间错误,我无法针对 HttpException 参考专门解决该错误。
var httpException = exception as HttpException;
我正在使用 C#,我只看到 VB.NET 中使用的样式,因此预期的语法样式可能存在一些问题。更正建议一直尝试将 h 小写以使 httpException,但 HttpException 是预期的
以下是完整代码:
using System.Net;
using System.Net.Http;
using System.Web; // bad practice: not usually supposed to be used on non
// web application projects
using System.Web.Http.ExceptionHandling;
using WebApi2Book.Data.Exceptions;
namespace WebApi2Book.Web.Common.ErrorHandling
{
public class GlobalExceptionHandler : ExceptionHandler
{
public override void Handle(ExceptionHandlerContext context)
{
var exception = context.Exception;
var httpException = exception as HttpException; <- red squiggle
if (httpException != null)
{
context.Result = new SimpleErrorResult(context.Request, (HttpStatusCode)httpException.GetHttpCode(), httpException.Message);
return;
}
if (exception is RootObjectNotFoundException)
{
context.Result = new SimpleErrorResult(context.Request, HttpStatusCode.NotFound, exception.Message);
return;
}
if (exception is ChildObjectNotFoundException)
{
context.Result = new SimpleErrorResult(context.Request, HttpStatusCode.Conflict, exception.Message);
return;
}
context.Result = new SimpleErrorResult(context.Request, HttpStatusCode.InternalServerError, exception.Message);
}
}
}
答:
评论