如何在 ASP.NET 对象的 ASP.NET 核心 Web API 控制器中抛出异常?

How can I throw an exception in an ASP.NET Core WebAPI controller that returns an object?

在 Framework WebAPI 2 中,我有一个如下所示的控制器:

[Route("create-license/{licenseKey}")]
public async Task<LicenseDetails> CreateLicenseAsync(string licenseKey, CreateLicenseRequest license)
{
    try
    {
        // ... controller-y stuff
        return await _service.DoSomethingAsync(license).ConfigureAwait(false);
    }
    catch (Exception e)
    {
        _logger.Error(e);
        const string msg = "Unable to PUT license creation request";
        throw new HttpResponseException(HttpStatusCode.InternalServerError, msg);
    }
}

果然,我收到了 500 错误消息。

如何在 ASP.NET Core Web API 中做类似的事情?

HttpRequestException 似乎不存在。我宁愿继续返回对象而不是 HttpRequestMessage.

像这样的事情呢。创建一个中间件,您将在其中公开某些异常消息:

public class ExceptionMiddleware
{
    private readonly RequestDelegate _next;

    public ExceptionMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        try
        {
            await _next(context);
        }
        catch (Exception ex)
        {
            context.Response.ContentType = "text/plain";
            context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;

            if (ex is ApplicationException)
            {
                await context.Response.WriteAsync(ex.Message);
            }
        }
    }
}

在您的应用中使用它:

app.UseMiddleware<ExceptionMiddleware>();
app.UseMvc();

然后在您的操作中抛出异常:

[Route("create-license/{licenseKey}")]
public async Task<LicenseDetails> CreateLicenseAsync(string licenseKey, CreateLicenseRequest license)
{
    try
    {
        // ... controller-y stuff
        return await _service.DoSomethingAsync(license).ConfigureAwait(false);
    }
    catch (Exception e)
    {
        _logger.Error(e);
        const string msg = "Unable to PUT license creation request";
        throw new ApplicationException(msg);
    }
}

更好的方法是 return 和 IActionResult。这样你就不必抛出异常。像这样:

[Route("create-license/{licenseKey}")]
public async Task<IActionResult> CreateLicenseAsync(string licenseKey, CreateLicenseRequest license)
{
    try
    {
        // ... controller-y stuff
        return Ok(await _service.DoSomethingAsync(license).ConfigureAwait(false));
    }
    catch (Exception e)
    {
        _logger.Error(e);
        const string msg = "Unable to PUT license creation request";
        return StatusCode((int)HttpStatusCode.InternalServerError, msg)
    }
}

最好不要在每个动作中捕获所有异常。只需捕获您需要专门做出反应的异常,然后在 .

中捕获(并包装到 HttpResponse)所有其他内容