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()
            {
     
  • 相关阅读:
    Android Logcat使用技巧
    SqlClient使用存储过程并获取输出参数的指
    内存调试的东西D/dalvikvm( 809 ): GC_CONCURRENT freed
    android 读写sd卡的权限设置
    Android中EditText的使用方法持續更新
    RSL编译方式的FLEX站点出现#2046错误
    从网络读取数据并动态的显示在ListView中
    LEFT JOIN INNER JOIN 效率比较
    使用Installshield2009 在IIS6部署Asp.net mvc 应用程序
    Installshield2009中使用osql.exe执行数据库脚本
  • 原文地址:https://www.cnblogs.com/liulun/p/2582733.html
Copyright © 2011-2022 走看看