在 C# 中通过 HttpWebRequest 进行 OData 调用时如何捕获 ODataErrorException?

How to catch ODataErrorException when I am making an OData call through HttpWebRequest in C#?

我正在尝试使用 C# 从我的 .Net 控制台应用程序调用 OData 服务。 我正在使用 HttpWebRequest 进行调用。

现在,如果存在特定于 OData 的错误,例如无效的 JSON 负载,则会从 OData 服务器抛出 ODataErrorException。

我的问题是如何捕获 ODataErrorException 并从中提取正确的消息?异常在 WebException catch 块中被捕获,它只显示“400 Bad Request”。但它并没有告诉我实际的错误原因。 如果我通过 Postman 进行相同的调用,那么它会给我一个正确的异常结果。

我的代码:-

                byte[] byteArray;
                Stream requestDataStream;
                WebResponse webResponse;
                Stream dataStream;
                StreamReader reader;

                string ODataUrl = "https://someodata.com/data/someentity";

                string jsonPayloadData = "{,\"Key1\":\"Value1\",\"Key2\":\"Value2\",\"Key3\":\"Value3\"}";   /*** a deliberate comma is placed at the start ***/

                byteArray = System.Text.Encoding.UTF8.GetBytes(jsonPayloadData);

                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(ODataUrl);
                request.Method = "POST";
                request.ContentType = "application /json;charset=utf-8";
                request.Accept = "application /json";
                request.Headers.Add("Authorization", authHeader);
                request.ContentLength = byteArray.Length;
                requestDataStream = request.GetRequestStream();

                requestDataStream.Write(byteArray, 0, byteArray.Length);
                requestDataStream.Close();

                webResponse = request.GetResponse();
                string desc = ((HttpWebResponse)webResponse).StatusDescription;
                // Get the stream containing content returned by the server.  
                dataStream = webResponse.GetResponseStream();
                // Open the stream using a StreamReader for easy access.  
                reader = new StreamReader(dataStream);
                // Read the content.  
                string jsonData = reader.ReadToEnd();
                Console.WriteLine(jsonData);
                Console.ReadLine(); 
            }
            catch(ODataErrorException ex)
            {
                Console.WriteLine(ex.Message);
            }
            catch (WebException ex)
            {
                /**** I want to get an ODataErrorException here ****/
                while(ex != null)
                {
                    string message = ex.Message;
                    Console.WriteLine(message);
                    ex = (WebException)ex.InnerException;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

这将抛出一个异常(因为有效负载中的冗余逗号),该异常到达 WebException catch 块。但它只给我 "400 Bad Request"。但是我想得到真正的异常原因,就像Postman一样。

Postman 的相同请求给了我这个:-

{
"error": {
    "code": "",
    "message": "An error has occurred.",
    "innererror": {
        "message": "Invalid property identifier character: ,. Path '', line 1, position 1.",
        "type": "Newtonsoft.Json.JsonReaderException",
        "stacktrace": " ...some long stack ..."
    }
}}

在您的 catch 块中尝试以下代码:

        catch (WebException webEx)
        {
            if (0 != webEx.Response.ContentLength)
            {
                using (var stream = webEx.Response.GetResponseStream())
                {
                    if (null != stream)
                    {
                        using (var reader = new StreamReader(stream))
                        {
                            var errorMsg = reader.ReadToEnd();
                        }
                    }
                }
            }
        }