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

swa*_*nee 9 json asp.net-web-api asp.net-core-mvc asp.net-core

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

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

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

    // Add MVC to the request pipeline.
    app.UseMvc();
Run Code Online (Sandbox Code Playgroud)

我想普遍地设置它.有没有"正确/最好"的方法在MVC 6中为API设置它?

谢谢...

Kir*_*lla 13

实现您的场景的一种方法是编写一个ExceptionFilter并在该捕获中获取必要的细节并将其设置Result为a 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
        };
    }
}
Run Code Online (Sandbox Code Playgroud)

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

app.UseServices(services =>
{
    services.AddMvc();
    services.Configure<MvcOptions>(options =>
    {
        options.Filters.Add(new CustomExceptionFilterAttribute());
    });
.....
}
Run Code Online (Sandbox Code Playgroud)

请注意,此解决方案并未涵盖所有方案...例如,在格式化程序编写响应时抛出异常.