简体   繁体   English

在 .NET 中使用 WebClient 发送 PATCH 请求

[英]Sending PATCH request using WebClient in .NET

I have an older ASP.NET WebForms site.我有一个较旧的 ASP.NET WebForms 站点。 I am trying to use WebClient to send a PATCH request to a REST API:我正在尝试使用WebClient向 REST API 发送PATCH请求:

using (WebClient client = new WebClient())
{
    client.Headers[HttpRequestHeader.Authorization] = "Bearer " + authToken;
    try
    {
        responseString = Encoding.UTF8.GetString(client.UploadValues(endpoint, "PATCH", body));
    }                
    catch (Exception e)
    {
        return e;
    }            
}

In this snippet, endpoint is the URI I'm PATCH -ing to, and body is a NameValueCollection .在此代码段中, endpoint是我要PATCH的 URI,而bodyNameValueCollection

This gives me an HTTP 400 "Bad Request" error.这给了我一个 HTTP 400“错误请求”错误。 If I drill down in the exception, it indicates a protocol violation.如果我深入了解异常,则表明存在协议违规。 I have tried adding a header for content-type, but that did not help.我尝试为内容类型添加 header,但这没有帮助。

This same code does work for POST requests, and it's how I'm getting my access token successfully.相同的代码适用POST请求,这就是我成功获取访问令牌的方式。 But it does not work for PATCH .但它不适用于PATCH Is there any way to send a valid PATCH request using WebClient ?有没有办法使用WebClient发送有效的PATCH请求?

I realize there are other libraries out there, but if possible, I'd like to be consistent with the rest of the code in this class in using WebClient .我意识到那里还有其他库,但如果可能的话,我想在使用WebClient时与此 class 中代码的 rest 保持一致。 If I have to switch to something else, I'd want to update the rest of the code too.如果我必须切换到其他东西,我也想更新代码的 rest。

Update更新

Yes, the API does support PATCH .是的,API 确实支持PATCH It's the Microsoft Graph API and PATCH works fine with Postman.它是 Microsoft Graph API 和 PATCH 与 Postman 配合得很好。

It looks ok.看起来不错。 If the API supports PATCH you should receive a response.如果 API 支持 PATCH,您应该会收到响应。 Could you check if PATCH is implemented on the API?您能否检查一下 API 上是否实施了 PATCH?
Another possibility is that you violate some validation rules applied in PATCH method.另一种可能性是您违反了 PATCH 方法中应用的一些验证规则。

I got it to work using the UploadString method, as follows:我使用UploadString方法让它工作,如下所示:

using (WebClient client = new WebClient())
{
    client.Headers[HttpRequestHeader.Authorization] = "Bearer " + authToken;
    try
    {
        client.Headers[HttpRequestHeader.ContentType] = "application/json";
        responseString = client.UploadString(endpoint, method, body);
    }                
    catch (Exception e)
    {
        return e;
    }            
}

Where body is a JSON-formatted string, instead of a NameValueCollection as I was trying initially.其中body是 JSON 格式的字符串,而不是我最初尝试的NameValueCollection I'm not sure if there's a better way to do this, but it seems to be working now.我不确定是否有更好的方法来做到这一点,但它现在似乎正在工作。

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

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