简体   繁体   English

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

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

In Framework WebAPI 2, I have a controller that looks like this: 在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);
    }
}

Sure enough, I get back a 500 error with the message. 果然,我收到消息的500错误。

How can I do something similar in ASP.NET Core Web API? 如何在ASP.NET Core Web API中执行类似的操作?

HttpRequestException doesn't seem to exist. HttpRequestException似乎不存在。 I would prefer to continue returning the object instead of HttpRequestMessage . 我宁愿继续返回对象而不是HttpRequestMessage

What about something like this. 这样的事情呢。 Create a middleware where you will expose certain exception messages: 创建一个中间件,您将在其中公开某些异常消息:

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

Use it in your app: 在您的应用中使用它:

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

And then in your action throw the exception: 然后在你的行动中抛出异常:

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

A better approach is to return an IActionResult . 更好的方法是返回IActionResult That way you dont have to throw an exception around. 这样你就不必抛出异常了。 Like this: 像这样:

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

It's better not to catch all exceptions in every action. 最好不要在每个动作中捕获所有异常。 Just catch exceptions you need to react specifically and catch (and wrap to HttpResponse) all the rest in Middleware . 只需捕获需要特别反应的异常并捕获(并包装到HttpResponse) 中间件中的所有其他内容。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 asp.net 内核中捕获或抛出异常? - How do i catch or throw an exception in asp.net core? 如何在 asp.net core webapi 控制器中读取请求正文? - How to read request body in an asp.net core webapi controller? ASP.NET Core 3.0 WebAPI - 为什么在控制器方法中处理异常时我仍然收到 InternalServerError? - ASP.NET Core 3.0 WebAPI - why do I still receive InternalServerError when exception is handled in the Controller Method? 如何将 Typescript Map 对象发布到 ASP.Net Core WebAPI? - How to post Typescript Map object to ASP.Net Core WebAPI? 如何在 ASP.NET 核心 Controller 上允许 /(斜线)? - How can i allow /(slash) on ASP.NET Core Controller? 如何在 ASP.NET Core 3.1 WebApi 中使用自定义记录器登录一些不同的文件? - How can i log in some different files with custom logger in ASP.NET Core 3.1 WebApi? 如何转换将JSON返回列表的ASP.NET WebAPI调用? - How can I convert a ASP.NET WebAPI calls that returns JSON into a list? 如何在 asp.net 内核的基础 controller 中处理 On Exception? - How to handle On Exception in the base controller of asp.net core? 如何在asp.net核心webapi项目中如何将多个参数传递给控制器​​,其中一个参数是文件或字节[] - How in asp.net core webapi project you can pass multiple parameters to a controller where one of them is file or a byte[] Asp.Net Core Url.Action使用WebApi控制器 - Asp.Net Core Url.Action use WebApi Controller
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM