简体   繁体   English

如何在添加文件后但在发送之前获取 RestRequest 正文内容

[英]How to get the RestRequest body content after adding file but before sending

I am calling an API that requires an MD5 hash of the body of the request in the request's header.我正在调用一个 API,该 API 需要请求标头中请求正文的 MD5 哈希值。

I am using RestSharp to send the requests.我正在使用 RestSharp 发送请求。 Normally I can check the Request.Parameters for the Body parameter and hash the value of the parameter before calling Execute.通常我可以在调用 Execute 之前检查 Body 参数的 Request.Parameters 并散列参数的值。

Although, after calling AddFile the body parameter is empty and appears to stay empty until the content is prepared before sending the request.虽然,在调用 AddFile 之后,body 参数为空,并且在发送请求之前准备好内容之前一直保持为空。 (Since files are stored separately) (因为文件是分开存储的)

Is there anyway to read the body content of the RestRequest after the multipart string has been generated but before the request is sent so I can add the MD5 hash to the header of the request?无论如何在生成多部分字符串之后但在发送请求之前读取 RestRequest 的正文内容,以便我可以将 MD5 哈希添加到请求的标头中?

I realize this is an old question but I think the library handles this for you by allowing you access to the Http object before sending the request.我意识到这是一个老问题,但我认为库通过允许您在发送请求之前访问Http对象来为您处理这个问题。

var client = new RestSharp.RestClient();

var request = new RestRequest();

request.OnBeforeRequest = (http) => {
    http.Headers.Add(new HttpHeader {
        Name = "CONTENT_MD5",
        Value = GenerateMd5Hash(x.RequestBody)
    });
}

From additional research I have done, it appears that at this time there is not a way to achieve the functionality that I was after with the default API.从我所做的其他研究来看,目前似乎没有办法实现我使用默认 API 所追求的功能。

I ended up downloading the source code and added an event handler to the Http class that is now triggered before the HttpWebRequest is sent.我最终下载了源代码,并向现在在发送 HttpWebRequest 之前触发的 Http 类添加了一个事件处理程序。 I send the HttpWebRequest in the parameters of the event handler which is then bubbled all the way up to the RestClient.我在事件处理程序的参数中发送 HttpWebRequest,然后一直冒泡到 RestClient。

I can then intercept the request in the top level code and add to the headers as I please before the request is sent.然后,我可以在顶级代码中拦截请求,并在发送请求之前根据需要添加到标头中。

This is probably not the most efficient modification but it works well enough for unit tests.这可能不是最有效的修改,但它对于单元测试来说效果很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM