简体   繁体   English

HttpWebRequest / Response引发错误“未找到”

[英]HttpWebRequest/Response throwing error “Not Found”

I am making an API call to a REST service. 我正在对REST服务进行API调用。 The REST service returns an XML string that contains a user token if the password submitted is correct, or an XML string with data if it isn't. 如果提交的密码正确,则REST服务返回包含用户令牌的XML字符串,否则返回包含数据的XML字符串。

Here is an example if the password is incorrect: 如果密码不正确,请参见以下示例:

<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<authenticationResponse>
  <statusCode>403</statusCode>
  <errors>
    <error>
       ....
    </error>
  </errors>
  <timestamp>2011-03-31 22:45:03 GMT</timestamp>
</authenticationResponse>

With this code below, it appears .NET is translating this to an actual error. 使用下面的代码,.NET似乎将其转换为实际错误。 I still want it to read the XML data and ignore any error: 我仍然希望它读取XML数据并忽略任何错误:

RequestData requestData = (RequestData)result.AsyncState;
HttpWebResponse response = 
                 (HttpWebResponse)requestData.Request.EndGetResponse(result);

How I can ignore the error but still create the stream to read the XML? 如何忽略错误但仍创建流以读取XML?

Your code isn't translating this into an actual error - a HTTP status code of 403 is "Forbidden". 您的代码未将其转换为实际错误-HTTP状态代码403为“禁止”。

HTTP "Not Found" has a HTTP status code of 404 so it looks like the HTTP endpoint you're requesting doesn't exist in the REST service. HTTP“未找到”的HTTP状态代码为404因此看起来您请求的HTTP端点在REST服务中不存在。

Catch WebException, check the exception status, read the response. 捕获WebException,检查异常状态,读取响应。 See these questions for examples: 有关示例,请参见以下问题:

Ok so I figured it out, there's a few parts here. 好的,所以我知道了,这里有几个部分。

First off the API is generating that xml when the parameters passed don't meet whats expected. 首先,当传递的参数不符合预期时,API将生成该xml。 In this case, if the password is incorrect, it'll pass back the 403. 在这种情况下,如果密码不正确,它将传回403。

The error is an error, so the framework treats it as such, however the error contains a response anyways, you just have to get the response off the error. 错误是错误,因此框架将错误处理为错误,但是错误仍然包含响应,您只需要从错误中获取响应即可。 This is essentially the answer to the question. 从本质上讲,这就是问题的答案。 Have to catch it the error and snag the response off the error to read the data in the stream, which is what Mauricio was getting to. 必须捕获错误并捕获错误响应才能读取流中的数据,这是Mauricio要做的。

Essentially, I guess all the answers here are correct, or pieces of it, just took a little digging to put it all together. 从本质上讲,我想这里的所有答案都是正确的,或者只是部分答案,只是花了一点力气才把它们放在一起。

Thanks Guys. 多谢你们。

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

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