从Asp.Net MVC 6 API返回JSON错误

我正在尝试使用MVC 6构建一个Web API.但是当我的一个控制器方法抛出一个错误时,响应的内容一个格式很好的 HTML页面,这是一个非常丰富的MVC应用程序.但是,由于这是一个API,我宁愿返回一些 JSON.

注意:我的设置现在超级基本,只需设置:

app.UseStaticFiles();
    app.UseIdentity();

    // Add MVC to the request pipeline.
    app.UseMvc();

我想要普遍设置这个.是否有一个“正确/最好”的方法来设置在MVC 6中的一个API?

谢谢…

解决方法

实现您的方案的一种方法是编写一个ExceptionFilter,并捕获必要的细节,并将Result设置为JsonResult.
// Here I am creating an attribute so that you can use it on specific controllers/actions if you want to.
public class CustomExceptionFilterattribute : ExceptionFilterattribute
{
    public override void OnException(ExceptionContext context)
    {
        var exception = context.Exception;
        context.Result = new JsonResult(/*Your POCO type having necessary details*/)
        {
            StatusCode = (int)HttpStatusCode.InternalServerError
        };
    }
}

您可以将此异常过滤器添加到适用于所有控制器.
例:

app.UseServices(services =>
{
    services.AddMvc();
    services.Configure<Mvcoptions>(options =>
    {
        options.Filters.Add(new CustomExceptionFilterattribute());
    });
.....
}

请注意,此解决方案不涵盖所有方案…例如,当由格式化程序写入响应时抛出异常.

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....