[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);
}
}
像这样的东西呢。创建一个中间件,在其中您将公开某些异常消息:
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);
}
}
[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)
}
}
但这无济于事,仍然令人崩溃。 我在考虑make try{}catch返回500,并在每个过滤器中进行某种日志记录,但这将导致大量的重复。 有什么办法可以在全球范围内处理吗? MVC服务的添加方式如下:
知道如何正确设置控制器描述吗? 谢谢,马里奥
在常规MVC控制器中,我们可以使用输出pdf。 但是如何将其更改为呢? So上也有一篇类似的文章:在ASP.NET Web API中从控制器返回二进制文件。它讨论输出一个现有的文件。但我不能让它和溪流一起工作。 有什么建议吗?
我想在ASP.NET Web API控制器中返回一个文件,但我的所有方法都将作为JSON返回。 当我在浏览器中调用这个endpoint时,Web API将返回为JSON,HTTP内容头设置为。