zoukankan      html  css  js  c++  java
  • 【翻译】ASP.NET WEB API异常处理

    当一个web api抛出一个异常后

    此异常会被转化成一个HTTP响应

    错误代码为500的服务错误

    但是如果你不想让客户端看到500的错误码

    你也可以自定义错误码

    如下代码当用户输入的ID没有与之相关的数据

    则返回了错误码为404的错误

    (页面未找到)

    public Product GetProduct(int id) 
    { 
        Product item = repository.Get(id); 
        if (item == null) 
        { 
            throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound)); 
        } 
        return item; 
    }
     

    如果需要进一步自定义错误消息的内容

    可以通过如下方法来完成

    public Product GetProduct(int id) 
    { 
        Product item = repository.Get(id); 
        if (item == null) 
        { 
            var resp = new HttpResponseMessage(HttpStatusCode.NotFound) 
            { 
                Content = new StringContent(string.Format("No product with ID = {0}", id)), 
                ReasonPhrase = "Product ID Not Found" 
            } 
            throw new HttpResponseException(resp); 
        } 
        return item; 
    }
     

    结果如下图所示

    image

    image

    另外

    开发人员可以托管异常的抛出

    异常过滤器可以接到controller抛出的任何未处理异常,

    并不单单是HttpResponseException

    异常过滤器实现了System.Web.Http.Filters.IExceptionFilter接口

     using System; 
        using System.Net; 
        using System.Net.Http; 
        using System.Web.Http.Filters; 
     
        public class NotImplExceptionFilter : ExceptionFilterAttribute  
        { 
            public override void OnException(HttpActionExecutedContext context) 
            { 
                if (context.Exception is NotImplementedException) 
                { 
                    context.Response = new HttpResponseMessage(HttpStatusCode.NotImplemented); 
                } 
            } 
        } 
    
     

    光创建了异常过滤器还不够

    还要注册到系统中去才有效

        public class WebApiApplication : System.Web.HttpApplication
        {
            static void ConfigureApi(HttpConfiguration config)
            {
                config.Filters.Add(new HelloWebAPI.Controllers.NotImplExceptionFilter());
            } 
            protected void Application_Start()
            {
                AreaRegistration.RegisterAllAreas();
    
                ConfigureApi(GlobalConfiguration.Configuration);
                FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
                RouteConfig.RegisterRoutes(RouteTable.Routes);
                BundleConfig.RegisterBundles(BundleTable.Bundles);
            }
        }
     

    我目前还不知道怎么在这里注册这个过滤器

    image

    运行的效果如下

    image

    image

    另外

    如果知识针对某个类或者某个action处理异常

    也可以使用特性的写法

            [NotImplExceptionFilter]
            public IEnumerable<Product> AllProducts()
            {
     
  • 相关阅读:
    Apache 配置多个HTTPS站点(转载)
    一个显示某段时间内每个月的方法 返回由这些月 (转载)
    支付宝支付出现 openssl_sign(): supplied key param cannot be coerced into a private key
    tp5 setInc 中一直返回 0
    数据库 SQLSTATE[22003]: Numeric value out of range: 1264 Out of range value for col
    MYSQL设置查询内存表大小
    PHP原生的mysql查询
    支付宝 APP支付 错误码
    centos6.5中安装完成扩展后 在modules 也能找到 但是在phpinfo中看不见
    configure: error: Cannot find php-config. Please use --with-php-config=PATH
  • 原文地址:https://www.cnblogs.com/fx2008/p/2817318.html
Copyright © 2011-2022 走看看