升级到 .Net 6 后,system.web 不再包含 HttpException

After upgrading to .Net 6, system.web no longer contains HttpException

在旧版本的 .Net Core 中,我可以这样做来抛出异常:

public class MyParentController : Microsoft.AspNetCore.Mvc.Controller
{
    protected virtual GamePlayer CurrentPlayer => Players.GetPlayer(Session) ?? throw MyCustomHttpException(HttpStatusCode.Unauthorized, "Unauthorized");

    protected Exception MyCustomHttpException(HttpStatusCode code, String msg) => throw new System.Web.HttpException(code.ToString(), Int32.Parse(msg));
}

但是在将我的解决方案升级到 .Net 6 之后,出现了这个错误:

The type or namespace name HttpException does not exist in System.Web

新的 .Net 不提供这样的东西吗?

谢谢!

在你的情况下你应该这样做:

public class MyParentController : Microsoft.AspNetCore.Mvc.Controller
{
    [HttpGet("CurrentPlayer")]
    public IActionResult GetCurrentPlayer() 
    {
        var player = Players.GetPlayer(Session);
        return player != null ? Json(player) : Unauthorized();
    }
}

HttpException Class 只存在于 .net 框架中,我想你的项目是一个 ASP.Net 项目?

https://docs.microsoft.com/en-us/dotnet/api/system.web.httpexception?view=netframework-4.8

为了处理 .net 6.0 中的错误,我想你可以阅读文档:

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/error-handling?view=aspnetcore-6.0