如何在返回对象的ASP.NET Core WebAPI控制器中抛出异常?

时间:2017-04-12 00:17:55

标签: c# asp.net-core-webapi

在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

2 个答案:

答案 0 :(得分:13)

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

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);
    }
}

更好的方法是返回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)
    }
}

答案 1 :(得分:5)

最好不要在每个动作中捕获所有异常。只需捕获您需要特别做出反应的异常并捕获(并包装到HttpResponse)Middleware中的所有其余内容。