It would be nice if there were some way of turning off "throw on non-success code" but if you catch WebException you can at least use the response:
using System;
using System.IO;
using System.Web;
using System.Net;
public class Test
{
static void Main()
{
WebRequest request = WebRequest.Create("http://csharpindepth.com/asd");
try
{
using (WebResponse response = request.GetResponse())
{
Console.WriteLine("Won't get here");
}
}
catch (WebException e)
{
using (WebResponse response = e.Response)
{
HttpWebResponse httpResponse = (HttpWebResponse) response;
Console.WriteLine("Error code: {0}", httpResponse.StatusCode);
using (Stream data = response.GetResponseStream())
using (var reader = new StreamReader(data))
{
string text = reader.ReadToEnd();
Console.WriteLine(text);
}
}
}
}
}
You might like to encapsulate the "get me a response even if it's not a success code" bit in a separate method. (I'd suggest you still throw if there isn't a response, e.g. if you couldn't connect.)
If the error response may be large (which is unusual) you may want to tweak HttpWebRequest.DefaultMaximumErrorResponseLength
to make sure you get the whole error.
So, I just ended up doing this, Interface:
[OperationContract]
[WebInvoke(Method = "POST",
UriTemplate = "LoggingTest/{logID}/{logLevel}?errorCode={errorCodeInt}",
BodyStyle = WebMessageBodyStyle.Bare)]
void LoggingTest(string logID, string logLevel, int errorCodeInt, Stream message);
Implementation:
public void LoggingTest(string logID, string logLevel, int errorCodeInt, Stream message)
{
switch (logLevel)
{
case "error":
log.Error(errorCodeInt, message, null);
break;
case "warn":
log.Warn(errorCodeInt, message, null);
break;
case "info":
log.Info(errorCodeInt, message, null);
break;
case "debug":
log.Debug(errorCodeInt, message, null);
break;
}
}
And now it works. Must have something to do with the parameters being passed in the UriTemplate, because when I changed it to pass the parameters like so:
UriTemplate = "LoggingTest/{logID}/{logLevel}?errorCode={errorCodeInt}",
it started accepting the POST.
Edit 7/7: Here's the final JavaScript also:
jqueryPost('LoggingTest/LogID/debug?errorCode=0', { message: 'this is a test message'} ;
function jqueryPost(url, message) {
$.post(url, message);
}
Best Answer
You need to encode the parameter: