English 中文(简体)
HTTP POST 追溯性减员作为同化处理错误
原标题:HTTP POST Reactive Extention async. pattern handle errors

我试图使用以下法典,但在出现例外情况时,它并不发挥作用。 谁能帮助我这样做? i 试图将网络例外放在鱼群中。 有可能将分散的数据类型退回(而不仅仅是说明)。

IObservable<string> tempReturnData = null;
        try
        {
            // create http web request
            HttpWebRequest WSrequest = (HttpWebRequest)WebRequest.Create(WebURL);
            // instantiate Request class object
            RequestState rs = new RequestState();
            rs.Request = WSrequest;
            // Lock current webrequest object.. incase of retry attempt 
            lock (WSrequest)
            {
                rs.Request.ContentType = "application/x-www-form-urlencoded";
                rs.Request.Method = "POST";
                rs.Request.Timeout = 100;
                // bug in .net that closes the connection prior to it being finished 
                rs.Request.KeepAlive = false;
                rs.Request.ProtocolVersion = HttpVersion.Version10;
                // async pattern get request
                var fetchRequestStream = Observable.FromAsyncPattern<Stream>(rs.Request.BeginGetRequestStream, rs.Request.EndGetRequestStream);
                // async pattern get response
                var fetchResponse = Observable.FromAsyncPattern<WebResponse>(rs.Request.BeginGetResponse, rs.Request.EndGetResponse);
                // 
                tempReturnData = (from tempResult in fetchRequestStream() select tempResult).SelectMany(stream =>
                    {
                        using (var writer = new StreamWriter(stream)) writer.Write(postData);
                        // here i wants to catch web exception in fetchResponse()   FYI : in my function i am returning IObservable<string>
                        return fetchResponse().Catch(Observable.Empty<WebResponse>()).Retry(5);
                    }).Select(result =>
                    {
                        lock (rs)
                        {
                            rs.Response = (HttpWebResponse)result;

                            string s = "";
                            // if response is ok then read response stream data
                            if (rs.Response.StatusCode == HttpStatusCode.OK)
                            {
                                using (StreamReader reader = new StreamReader(rs.Response.GetResponseStream())) s = reader.ReadToEnd();
                            }
                            // Error case if error occurs then try after random time period
                            else
                            {
                                if (Attempt < appConfig.PSPRequestAttempt)
                                {
                                    Attempt++;
                                    RandomisePost(WebURL, postData, Attempt);
                                }
                            }
                            return s;
                        }
                    }); // get response stream data
                return tempReturnData;
            }
        }
        catch (Exception ex)
        {
            // Debug.WriteLine("Exception Occurs   " + ex.Message);
            return null;
        }
最佳回答

我认为,你为把《乐施法》和非《乐施法》混为一谈而努力。 敬请您 Rx代码按简单的Rx查询方式开展工作,例如:

    return
        from st in fetchRequestStream()
        from rp in postDataAndFetchResponse(st)
        from s in fetchResult(rp)
        select s;

This query relies on three functions that look like this: Func<X, IObservable<Y>>.

然后,你可以使用标准RX操作员处理所有再造和例外处理。 无需做任何不可靠的“文明”电话!

You can call it like this:

FetchStringFromPost("url", "postData")
.Retry(3)
.Subscribe(s => { }, ex =>
{
    /* Exceptions here! */
}, () => { });

全文如下:

public IObservable<string> FetchStringFromPost(string WebURL, string postData)
{
    var request = (HttpWebRequest)WebRequest.Create(WebURL);
    request.ContentType = "application/x-www-form-urlencoded";
    request.Method = "POST";
    request.Timeout = 100;
    request.KeepAlive = false;
    request.ProtocolVersion = HttpVersion.Version10;

    var fetchRequestStream = Observable
        .FromAsyncPattern<Stream>(
            request.BeginGetRequestStream,
            request.EndGetRequestStream);

    var fetchResponse = Observable
        .FromAsyncPattern<WebResponse>(
            request.BeginGetResponse,
            request.EndGetResponse);

    Func<Stream, IObservable<HttpWebResponse>> postDataAndFetchResponse = st =>
    {
        using (var writer = new StreamWriter(st))
        {
            writer.Write(postData);
        }
        return fetchResponse().Select(rp => (HttpWebResponse)rp);
    };

    Func<HttpWebResponse, IObservable<string>> fetchResult = rp =>
    {
        if (rp.StatusCode == HttpStatusCode.OK)
        {
            using (var reader = new StreamReader(rp.GetResponseStream()))
            {
                return Observable.Return<string>(reader.ReadToEnd());
            }
        }
        else
        {
            var msg = "HttpStatusCode == " + rp.StatusCode.ToString();
            var ex = new System.Net.WebException(msg,
                WebExceptionStatus.ReceiveFailure);
            return Observable.Throw<string>(ex);
        }
    };

    return
        from st in fetchRequestStream()
        from rp in postDataAndFetchResponse(st)
        from s in fetchResult(rp)
        select s;
}

When I tested the above code I tried to call FetchStringFromPost("http://www.microsoft.com", "foo").Materialize() and got back this:

“WebException”/

Seems to work as a treatment. 让我知道你们是如何去的。

问题回答

暂无回答




相关问题
Manually implementing high performance algorithms in .NET

As a learning experience I recently tried implementing Quicksort with 3 way partitioning in C#. Apart from needing to add an extra range check on the left/right variables before the recursive call, ...

Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

How do I compare two decimals to 10 decimal places?

I m using decimal type (.net), and I want to see if two numbers are equal. But I only want to be accurate to 10 decimal places. For example take these three numbers. I want them all to be equal. 0....

Exception practices when creating a SynchronizationContext?

I m creating an STA version of the SynchronizationContext for use in Windows Workflow 4.0. I m wondering what to do about exceptions when Post-ing callbacks. The SynchronizationContext can be used ...

Show running instance in single instance application

I am building an application with C#. I managed to turn this into a single instance application by checking if the same process is already running. Process[] pname = Process.GetProcessesByName("...

How to combine DataTrigger and EventTrigger?

NOTE I have asked the related question (with an accepted answer): How to combine DataTrigger and Trigger? I think I need to combine an EventTrigger and a DataTrigger to achieve what I m after: when ...

热门标签