代码之家  ›  专栏  ›  技术社区  ›  Paul Meems

azure没有在httpexception中传递我的自定义消息

  •  1
  • Paul Meems  · 技术社区  · 7 年前

    我在azure webapp中有一个rest api。 当一个post被发送到我的端点时,我会做一些检查,如果需要,我会抛出一个httpexception:

    throw new HttpException(400, msgInfo);
    

    在哪里? msgInfo 是我的自定义消息。在使用visual studio 2015的开发机器中,我的回答是:

    {"Message":"An error has occurred.","ExceptionMessage":"[my custom message]","ExceptionType":"System.Web.HttpException","StackTrace":"..."}
    

    现在我可以向用户显示一条有用的消息。

    但在azure上,人们的反应是:

    {"Message":"An error has occurred."}
    

    所以没有自定义消息。

    很可能这是azure中的一个设置。我知道它不应该显示我的整个堆栈跟踪,但是它应该显示 ExceptionMessage .

    在我的 Web.config 我有:

    <system.web>
      <customErrors mode="RemoteOnly" />
    </system.web>
    
    <system.webServer>
        <httpErrors errorMode="Detailed" />
    </system.webServer>
    

    怎么解决这个问题?

    1 回复  |  直到 7 年前
        1
  •  1
  •   Joey Cai    7 年前

    对于在不同环境中如何显示错误详细信息,ASP.NET Web API有一个单独的配置。

    在你 HttpConfiguration ,有一个名为 IncludeErrorDetailPolicy . 这是它可能的价值。

    public enum IncludeErrorDetailPolicy
    {
        // Summary:
        //     Use the default behavior for the host environment. For ASP.NET hosting, usethe value from the customErrors element in the Web.config file. 
        //     For self-hosting, use the value System.Web.Http.IncludeErrorDetailPolicy.LocalOnly.
        Default = 0,
    
        // Summary:
        //     Only include error details when responding to a local request.
        LocalOnly = 1,
        //
        // Summary:
        //     Always include error details.
        Always = 2,
        //
        // Summary:
        //     Never include error details.
        Never = 3,
    }
    

    您可以配置如下:

    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.UseCloudServiceGateway();
    
            var config = new HttpConfiguration
            {
                IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always // Add this line to enable detail mode in release
            };
            WebApiConfig.Register(config);
            app.UseWebApi(config);
        }
    }
    

    有关更多详细信息,请参阅 thread .

    另外,你可以设置 <customErrors mode="Off"/> ,它指定禁用自定义错误。这个 detailed ASP.NET errors 显示给远程客户端和本地主机。