zoukankan      html  css  js  c++  java
  • ASP.NET mvc4 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()
            {
  • 相关阅读:
    流量调整和限流技术
    微软开源.NET Core的执行引擎CoreCLR{转载}
    Visual Studio 2015 前端开发工作流
    基于Redis的开源分布式服务Codis
    RemoteIE 开发者可跨平台使用IE测试网页
    参加MVP OpenDay 和2015 MVP Community Camp社区大课堂
    etcd:用于服务发现的键值存储系统
    Centos7下安装mono3.10.0
    在 Azure 上使用 Docker运行 Mono
    STOMP协议介绍
  • 原文地址:https://www.cnblogs.com/fx2008/p/3182421.html
Copyright © 2011-2022 走看看