I have a web method, which is called from jquery's ajax method, like this:
$.ajax({
type: "POST",
url: "MyWebService.aspx/DoSomething",
data: '{"myClass": ' + JSON.stringify(myClass) + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (result) {
alert("success");
},
error: function () {
alert("error");
}
});
And this is my web method:
[WebMethod(EnableSession = true)]
public static object DoSomething(MyClass myClass)
{
HttpContext.Current.Request.InputStream.Position = 0;
using (var reader = new StreamReader(HttpContext.Current.Request.InputStream))
{
Logger.Log(reader.ReadToEnd());
}
}
If myClass in javascript is serialized to correct format, then DoSomething methods executes and saves the raw json to database. But if myClass is in wrong then the method doesn't execute at all and I can't log the problematic json...
What is the best way to always somehow get and log the raw json, that my web method receives, even if the serialization fails?
With the help of some other answers on stackoverflow I came to this:
public class RequestLogModule : IHttpModule
{
private HttpApplication _application;
public void Dispose()
{
}
public void Init(HttpApplication context)
{
_application = context;
_application.BeginRequest += ContextBeginRequest;
}
private void ContextBeginRequest(object sender, EventArgs e)
{
var request = _application.Request;
var bytes = new byte[request.InputStream.Length];
request.InputStream.Read(bytes, 0, bytes.Length);
request.InputStream.Position = 0;
string content = Encoding.UTF8.GetString(bytes);
Logger.LogRequest(
request.UrlReferrer == null ? "" : request.UrlReferrer.AbsoluteUri,
request.Url.AbsoluteUri,
request.UserAgent,
request.UserHostAddress,
request.UserHostName,
request.UserLanguages == null ? "" : request.UserLanguages.Aggregate((a, b) => a + "," + b),
request.ContentType,
request.HttpMethod,
content
);
}
}
And in the web.config:
<httpModules>
<add name="MyRequestLogModule" type="MyNamespace.RequestLogModule, MyAssembly"/>
</httpModules>
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