当我在C#中通过HttpWebRequest进行OData调用时,如何捕获ODataErrorException? [英] How to catch ODataErrorException when I am making an OData call through HttpWebRequest in C#?

查看:261
本文介绍了当我在C#中通过HttpWebRequest进行OData调用时,如何捕获ODataErrorException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to call an OData service from my .Net console application using c#. I am using HttpWebRequest to make the call.

现在,如果存在特定于OData的错误,例如无效的JSON有效负载,则会从OData服务器引发ODataErrorException.

Now if there is an OData specific error, for example, an invalid JSON payload, then an ODataErrorException is thrown from the OData server.

我的问题是如何捕获该 ODataErrorException 并从中提取适当的消息?异常被捕获在WebException catch块中,并且只向我显示"400错误的请求".但这并没有告诉我实际的错误原因. 如果我拨打相同的电话,例如邮递员,那么它会给我一个适当的异常结果.

My question is how to catch that ODataErrorException and extract the proper message out of it? The exception gets caught in WebException catch block, and it only shows me "400 Bad Request". But it doesn't show me the actual error reason. If I make the same call through, say Postman, then it gives me a proper exception result.

我的代码:-

                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错误的请求" .但是我想得到实际的异常原因,就像邮递员一样.

This will throw an exception (beacuse of the redundant comma in the payload) which comes to the WebException catch block. But it gives me only "400 Bad Request". But I want to get the actual exception reason, just like Postman.

邮递员的相同要求也给了我:-

The same request from Postman gives me this:-

{
"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块中尝试以下代码:

Try below code in your catch block:

        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();
                        }
                    }
                }
            }
        }

这篇关于当我在C#中通过HttpWebRequest进行OData调用时,如何捕获ODataErrorException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆