I have this class that I can use to make a request to different paths with different Request methods(GET, POST etc).
I just added try and catch to log errors, however I don't know how to handle the catch block? I can't return an empty HttpWebResponse. "Not intended to be used directly from the code"
private static HttpWebResponse HttpRequest(string method, string path)
{
try
{
var httpWebRequest =
(HttpWebRequest) WebRequest.Create(ConfigurationManager.AppSettings["server"] + path);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = method;
httpWebRequest.Credentials =
new NetworkCredential(ConfigurationManager.AppSettings["username"],
ConfigurationManager.AppSettings["password"]);
httpWebRequest.PreAuthenticate = true;
return (HttpWebResponse) httpWebRequest.GetResponse();
}
catch (Exception e)
{
Logger.Error(e, "HttpRequest error");
}
}
Any ideas?
Instead, you can return an HttpResponseMessage, and in a catch (Exception ex) return something like this:
var response = new HttpResponseMessage(HttpStatusCode.InternalServerError)
{
Content = new StringContent(string.Join(
Environment.NewLine,
ex.GetType().FullName,
ex.Message))
};
response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/plain");
return response;
(With ContentType and Content set to suit your purposes)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With