ASP.NET Web Service validating incoming XML - asp.net

I have ASP.NET 4 Web Service (asmx). I use IXmlSerializable interface for manually serialization/deserialization. In the function ReadXml (part of IXmlSerializable) I use functin XmlReader.ReadString and if client send me invalidate XML this function throw exception. How I validate incoming XMl before deserialization? Because exception is very hard operation for perfomance.

put the deserializatin in a try catch block and handle exception in catch. there is no point in validating xml upfront as it might through an exception when you attempt to validate as well.

Related

Getting HttpRequest from SignalR Hub

I have a web site with SignalR Hub (and jQuery code at the client for connecting).
I need to get the HttpRequest object for authentication.
The signalR have a Context.Request object(which is Microsoft.AspNet.SignalR.Owin.ServerRequest) but I can't find the way to convert it into an HttpRequest.
Does any one have an idea how to perform that?
Edit:
As it turns out, you can always go to HttpContext.Current and use the Request/Response object. But be careful, Not all reqular operations are supported, some of them will result in ThreadAborted Exception

ASP.NET DbSet Join

I have two classes, client and user. User is a field in client (there is a foreign key). I am trying to do a join, getting all the clients and the related user (it is one to one).
I am using Entity Framework and a web service that gives me my data.
I currently am getting all my clients like:
public DbSet<Client> getClients()
{
return context.Clients;
}
I need to also get the related object user. I found an example that tells me to do:
public DbSet<Client> getClients()
{
return context.Clients.include(x => x.User);
}
This throws an exception, I need to be working with IQueryable. If I change my function the connection to the web service does not work.
How do I do what I am trying to do?
EDIT:
The exception I get from the webservice is An error occurred while receiving the HTTP response to http://localhost:60148/WebService.svc. This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down). See server logs for more details.
try these links:
Expose IQueryable Over WCF Service
and IQueryable problems using WCF you need to send something else back, like a List, as IQueryable is actually a query, which you can't send back. the links above provide alternative ways to do it, to get around the IQueryable restriction.

How do I trap a SerializationException in Web API?

I have an ASP.NET Web API web service which throws a SerializationException in certain circumstances. The problem is that I'm unable to trap and log this exception server-side -- the only place it shows up is in the body of the HTTP response to the client.
I registered an ExceptionFilterAttribute as described in Exception Handling in ASP.NET Web API and verified that it works properly when I throw an exception within my controller. Unfortunately the SerializationException is being thrown during the response (after the controller) and appears to be completely swallowed up by ASP.NET. I also tried hooking Application_Error() in Global.asax.cs but it didn't show up there either.
How can I catch SerializationException exceptions during the Web API response?
If, instead of returning an object, you use the ApiController.CreateResponse() method and return a HttpResponseMessage you can then do response.Content.LoadIntoBufferAsync().Wait() and that will force the serialization to happen whilst you are still in the action and therefore can catch the exception.
BTW, Serialization of responses actually happens at the host layers(in HttpControllerHandler, when hosted in IIS and in HttpSelfhostServer, when hosted in SelfHost) which is way below the stack and not immediately after the response is returned from an action.
WebAPI Stack Poster: http://www.asp.net/posters/web-api/ASP.NET-Web-API-Poster-grayscale.pdf
That said, I am not able to come up with a straight forward way to achieve this. This is cumbersome, but may be override the default Xml and Json formatter's WriteToStreamAsync methods and try-catch-log any exceptions?
Alternatively, you can enable Web API Tracing which would log the exceptions happening during serialization. But yeah, if you do not know for the requests which cause the serialization errors, then you might want to enable tracing all the time which i am not sure is something you might want to do.
You can catch all Web API exceptions by registering an implementation of IExceptionHandler.
See Web API Global Error Handling
...there are a number of cases that exception filters can’t handle. For example:
Exceptions thrown from controller constructors.
Exceptions thrown from message handlers.
Exceptions thrown during routing.
Exceptions thrown during response content serialization .
One thing not mentioned in that article is that your IExceptionHandler must be registered, either by GlobalConfiguration.Configuration.Services.Add(...) or via an IoC container configured to be used by DependencyResolver.

Need parameter values of method where exception is thrown for logging without specific code in each method

How do I get current parameter values when an exception occurs inside a random method without having specific code in each method to write out the values?
I need this for ASP.NET MVC and WCF IErrorHandler?
For example given the following code:
public void SomeRandomMethod(Request request, string someRandomString)
{
throw new Exception();
}
is there a way for an IErrorHandler in WCF or MVC global.asax HttpApplication's Application_Error & Elmah to get the value of the Request object and someRandomString without specifically catching the exception and writing custom logic for each of N number of methods then throwing again?
Maybe this should be broken into 2 questions one for WCF and one for ASP>NET MVC?
The request hierarchies seem very similar to me and so I was hoping for a single unified answer.
I would recommend using Elmah. It's a wonderful logging tool for ASP.NET applications. It will include the parameters passed along with the HTTP request.

How to catch AJAX WebMethod errors in global.asax?

I'm using the common practice of catching errors in global.asax in my ASP.net application. In global.asax, I have a function Application_Error that logs the errors to the database.
This works very well to log errors that occur when the user requests a page.
However, this does nothing to help when an asynchronous method (a method decorated with the [WebMethod] attribute) called from the client-side throws an exception. The exception simply bubbles up and may be returned to the client-side code, but I would like to have the error handling code run on the server automatically similar to how page errors are logged in global.asax.
How do I accomplish this? One way would be to wrap every single asynchronous method with try-catch, but this doesn't seem like a good solution to me.
One option is to create an ASP.NET output filter that intercepts and logs WebMethod exceptions sent by ASP.NET to the client. Here's the basic idea:
Create a subclass of Stream that captures the content of the response.
When the stream is closed, check whether the response has a 500 status code as well as a "jsonerror: true" header. If so, the response contains a WebMethod exception; log the exception.
In Global.Application_PostMapRequestHandler, install an instance of this class as the output filter for JSON requests.
For complete source code, see this StackOverflow answer.
How to create a global exception handler for a Web Service

Resources