【问题标题】:Not getting REST WCF BadRequest error message in .NET 3.5在 .NET 3.5 中未收到 REST WCF BadRequest 错误消息
【发布时间】:2012-05-13 03:06:29
【问题描述】:

我有一个用 .NET 3.5 开发的 REST WCF 应用程序。

要检查无效的请求 url,例如缺少参数等。我正在使用一个实现“IErrorHandler”接口的类。所以在那个类里面我有这段代码应该生成一个 BadRequest 错误代码和消息:

public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
        {
            ExceptionHelper.HandleException(error, Severity.Error);
            StatusResponseBE statusResponseEntity = new StatusResponseBE();
            statusResponseEntity.Code = STATUS_CODE_FAIL;
            statusResponseEntity.Message = "Failed to perform requested operation";
            statusResponseEntity.Errors = new ErrorResponseBECollection();

            if (error is SerializationException || error is InvalidOperationException)
            {
                statusResponseEntity.Errors.Add(new ErrorResponseBE()
                {
                    Code = EX_INVALID_REQUEST_CODE,
                    Description = "Invalid Request"
                });
                fault = Message.CreateMessage(version, string.Empty, statusResponseEntity, new DataContractJsonSerializer(typeof(StatusResponseBE)));
                fault.Properties.Add(WebBodyFormatMessageProperty.Name, new WebBodyFormatMessageProperty(WebContentFormat.Json));
                WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.BadRequest;
                return;
            }
            else
            {
                statusResponseEntity.Errors.Add(new ErrorResponseBE()
                {
                    Code = EX_INTERNAL_ERROR_CODE,
                    Description = "Internal Error"
                });
                fault = Message.CreateMessage(version, string.Empty, statusResponseEntity, new DataContractJsonSerializer(typeof(StatusResponseBE)));
                fault.Properties.Add(WebBodyFormatMessageProperty.Name, new WebBodyFormatMessageProperty(WebContentFormat.Json));
                WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.InternalServerError;
                return;

            }

        }

但是当我使用无效请求 URL 访问 WCF 服务时,我收到 BadReqest 错误代码为 400,但响应 JSON 中没有消息,例如“代码:400;消息:无效请求”

HTTP/1.1 400 Bad Request
Cache-Control: private
Content-Type: application/xml; charset=utf-8
Server: Microsoft-IIS/7.0
Access-Control-Allow-Origin: *
X-AspNet-Version: 2.0.50727
Set-Cookie: ASP.NET_SessionId=xz412e35vruepr45qjrp5lyw; path=/; HttpOnly
X-Powered-By: ASP.NET
Date: Thu, 03 May 2012 14:47:15 GMT
Content-Length: 1165

<?xml version="1.0" encoding="utf-8"?><HTML><HEAD><STYLE type="text/css">#content{ FONT-SIZE: 0.7em; PADDING-BOTTOM: 2em; MARGIN-LEFT: 30px}BODY{MARGIN-TOP: 0px; MARGIN-LEFT: 0px; COLOR: #000000; FONT-FAMILY: Verdana; BACKGROUND-COLOR: white}P{MARGIN-TOP: 0px; MARGIN-BOTTOM: 12px; COLOR: #000000; FONT-FAMILY: Verdana}PRE{BORDER-RIGHT: #f0f0e0 1px solid; PADDING-RIGHT: 5px; BORDER-TOP: #f0f0e0 1px solid; MARGIN-TOP: -5px; PADDING-LEFT: 5px; FONT-SIZE: 1.2em; PADDING-BOTTOM: 5px; BORDER-LEFT: #f0f0e0 1px solid; PADDING-TOP: 5px; BORDER-BOTTOM: #f0f0e0 1px solid; FONT-FAMILY: Courier New; BACKGROUND-COLOR: #e5e5cc}.heading1{MARGIN-TOP: 0px; PADDING-LEFT: 15px; FONT-WEIGHT: normal; FONT-SIZE: 26px; MARGIN-BOTTOM: 0px; PADDING-BOTTOM: 3px; MARGIN-LEFT: -30px; WIDTH: 100%; COLOR: #ffffff; PADDING-TOP: 10px; FONT-FAMILY: Tahoma; BACKGROUND-COLOR: #003366}.intro{MARGIN-LEFT: -15px}</STYLE>
<TITLE>Request Error</TITLE></HEAD><BODY>
<DIV id="content">
<P class="heading1">Request Error</P>
<BR/>
<P class="intro">The server encountered an error processing the request. See server logs for more details.</P>
<P class="intro"></P>
</DIV>
</BODY></HTML>

相反,我在 Fiddler 的 Raw 选项卡中获得了上述内容。

知道为什么会发生这种情况以及我能做些什么来解决它吗?这一直困扰着我很多,我已经尝试了所有方法,但它似乎没有按预期工作。

【问题讨论】:

    标签: json wcf .net-3.5 fiddler bad-request


    【解决方案1】:

    试试这个

    var message = ex.GetOriginalMessage();
    var statusCode = (ex is MyDomainException || ex.GetType().IsSubclassOf(typeof (MyDomainException)))
                            ? HttpStatusCode.BadRequest
                            : HttpStatusCode.InternalServerError;
    
    var context = WebOperationContext.Current;
    
    if (context == null || context.IncomingRequest.ContentType.ToLower().Contains("json"))
        throw new WebProtocolException(statusCode, statusCode.ToString(), message, null);
    
    throw new WebProtocolException(statusCode, statusCode.ToString(), new XElement("Detail", message), false, null);
    

    【讨论】:

      【解决方案2】:

      这是我假设您用于该服务的 WebServiceHost 的问题。 WCF Rest Starter Kit 2 中的 WebServiceHost2 应该允许您通过抛出 WebProtocolExceptions 为您的错误指定自定义 json 负载

      您可以查看此以获取更多详细信息http://www.robbagby.com/rest/effective-error-handling-with-wcf-rest/

      【讨论】:

      • 感谢您的帮助,哈维。我正在为我当前的应用程序使用“System.ServiceModel.Activation.WebScriptServiceHostFactory”。当我尝试使用“Microsoft.ServiceModel.Web.WebServiceHost2Factory”时,我的应用程序根本没有响应。
      猜你喜欢
      • 2016-06-16
      • 2016-06-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多