Server was unable to process request. in web service method call - asp.net

Through my project i am making an web service call by adding web reference.
In my project i am creating object like below
PortalService portalService=new PortalService();
if (portalService != null)
{
DataSet ds = portalService.getStateList(3);
}
Its going inside if loop after creating object. But when calling web service method its giving me exception like below
[SoapException: Server was unable to process request. ---> Object reference not set to an instance of an object.]
Why this exception occuring? How do i make web service call?

The code is ok. It looks like there is an exception happening inside the service itself. I would look at the service code, and try to track down the issue. Perhaps the input is not valid?

Related

ASP Classic can I use Response.AppendToLog in global.asa Application_onStart

In ASP Classic can i use Response.AppendToLog in global.asa Application_onStart ?
I would try to Log error when application starts, but i always get this error:
erreur '8002802b'
/v1/common/CAppInit.asp, line 21
line 21:
Response.AppendToLog "INIT DB ERROR"
You can’t use the Response object in the global.asa file because there is no context for a response. The global.asa file deals with Application and Session level context.
If you think about it, when the application starts there doesn’t need to be a response because there is no initial request, it operates entirely outside of that pipeline.
The definition of the Response.AppendToLog() method is as follows;
The AppendToLog method adds a string to the end of the Web server log entry for the request.
This means that an initial request is required, which makes using it in the context of application startup impossible.
The usual solution is to implement a custom logging function that can be utilised inside the context of the Application or Session startup events.

Web API 'in memory' requests throw exception

Ok, my situation is much more complicated but there is an easy way to reproduce. Starting with a fresh new ASP.NET MVC 4 Web Application project and selecting Web API as a template I just add a second mvc action to the HomeController where I need to call Web API internally.
public async Task<string> TestAPI()
{
HttpServer server = new HttpServer(GlobalConfiguration.Configuration);
using (HttpMessageInvoker messageInvoker = new HttpMessageInvoker(server, false))
{
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "http://localhost:58233/api/values");
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = messageInvoker.SendAsync(request, new CancellationToken()).Result;
return await response.Content.ReadAsStringAsync();
}
//server.Dispose(); - if I do that on the second request I get a "Cannot access a disposed object." exception
}
that thing works only on the first request. On subsequent requests it throws with
The 'DelegatingHandler' list is invalid because the property
'InnerHandler' of 'RequestMessageHandlerTracer' is not null. Parameter
name: handlers
I really need to use the GlobalConfiguration.Configuration here since my system is very modular/plugin based, which makes it really hard to reconstruct that configuration within the action method(or anywhere else).
I would suggest trying to re-use the HttpServer instance on secondary requests. Creating and configuring a new server on every request is not an expected usage and you are likely hitting some edge case. Either setup a DI mechanism and inject into your controller a singleton of the HttpServer, or try accessing it from some static property.
I also would suggest using new HttpClient(httpServer) instead of HttpMessageInvoker.
The same issue can occur in Web API, if you have multiple HttpServers using the same configuration object, and the configuration contains a non-empty list of delegating handlers.
The error occurs because MVC/Web API builds a pipeline of handlers on first request, containing all the delegating handlers (eg RequestMessageHandlerTracer if request tracing is enabled) linked to each other, followed by the MVC server handler.
If you have multiple HttpServers using the same configuration object, and the config object contains delegating handlers, the first HttpServer will be successfully connected into a pipeline; but the second one won't, because the delegating handlers are already connected - instead it will throw this exception on first request/initialization.
More detail on the Web API case here (which is conceptually identical, but uses different classes and would have a slightly different fix):
webapi batching and delegating handlers
In my opinion, the MVC configuration classes should be pure config, and not contain actual delegating handlers. Instead, the configuration classes should create new delegating handlers upon initialization. Then this bug wouldn't exist.

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.

Error while calling webservice (Server was unable to process request. ---> PARAMETER_NAME)

I get this error while calling the web service hosted on the server.
The service has one web method with as string input and returns string (will be in XML format). The service is working fine but once in a while I get this error and can't predict. Can someone help me to get through this error.
Attached the screen shot of the error. Please let me know if you need additional info
I've never seen this error before, but I suggest you look at the event log on the server side. I suspect you are getting an unhandled exception on the client because you have one on the server.
Also, you should never return XML as a string. Use the XmlElement data type to return XML.

Null Reference getting REMOTE_ADDR

I have an ASMX web service running under IIS7 in classic mode. This service has the following code:
try
{
env.ExternalIP = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
catch (Exception ex)
{
LogWriter.WriteError(ex);
env.ExternalIP="000.000.000.000";
}
This results in the following stack trace. I only modified the names of usercode call stack here to protect the innocent:
Message: An Exception of type: NullReferenceException occured in method: GetAdditionalServerVar
ExceptionMsg: Object reference not set to an instance of an object.
===Stack Trace===
at System.Web.Hosting.ISAPIWorkerRequestInProc.GetAdditionalServerVar(Int32 index)
at System.Web.Hosting.ISAPIWorkerRequestInProc.GetServerVariable(String name)
at System.Web.HttpRequest.AddServerVariableToCollection(String name)
at System.Web.HttpRequest.FillInServerVariablesCollection()
at System.Web.HttpServerVarsCollection.Populate()
at System.Web.HttpServerVarsCollection.Get(String name)
at System.Collections.Specialized.NameValueCollection.get_Item(String name)
at MyService.MyMethod()
I'm at a loss here as this is very basic plain vanilla code.
EDIT
This gets even stranger. I have added some basic code just wondering what server variables I can get at this point. This fails with the same exception when I try and get all the keys:
System.NullReferenceException: Object
reference not set to an instance of an
object. at
System.Web.Hosting.ISAPIWorkerRequestInProc.GetAdditionalServerVar(Int32
index) at
System.Web.Hosting.ISAPIWorkerRequestInProc.GetServerVariable(String
name) at
System.Web.HttpRequest.AddServerVariableToCollection(String
name) at
System.Web.HttpRequest.FillInServerVariablesCollection()
at
System.Web.HttpServerVarsCollection.Populate()
at
System.Web.HttpServerVarsCollection.get_AllKeys()
at MyService.MyHelper()
When I was looking at the framework code looks like this could happen when the array which caches the server variables isn't populated and it looks like this occurs when there a null pointer to some Context...which seems like a fairly core piece of the framework code.
I suppose it's time to burn up one of our support tickets with Microsoft.
Going through my old questions. I believe this was caused by a bug in either .net or IIS. Essentially, the web service was marked as Oneway. By doing so the user was disconnected before the handler was executed so unless you managed to access the Request variables prior to the handler executing you would encounter a null reference exception.
The workaround was to add an HTTP module which accessed the property earlier in the pipeline before the client was sent the response and the handler was executed.
Have you tried getting the ip directly from HttpContext.Current.Request.UserHostAddress?
It seems that it is not always populated depending on the proxies... http://haacked.com/archive/2006/10/11/A_Gotcha_Identifying_the_Users_IP_Address.aspx

Resources