Catch Unauthorized exception - c#

I am connecting to a webservice in my project by entereing user credentials(user name and password) i need to catch a unauthorized exception when the user enter invalid username/password. How can i do that

Are you attempting to catch an exception before calling the webservice?
try
{
result = Service.GetResult(param1, param2);
}
catch(System.Net.WebException ex)
{
Logger.WriteError("Error calling Webservice: ", ex.ToString());
}
WebException will catch server return codes as errors I believe, such as HTTP status 404: Not Found etc.

Is your web service SOAP? Are you using WCF on on the service side? If so, take a look at a Specifying and Handling Faults

Related

Passing exception data between two applications

I don't know if this has been already answered or not. But, I am unable to find the example or cause of this problem.
Application 1:
try
{
//Read request and check for the request header element from the soap request
//validating request and salt
...here it might gets failed.
_requestValidationService.ValidateRequest();
}
catch (Exception ex)
{
ex.Data.Add("Exception", "test");
throw ex;
}
Application 2:
catch (Exception ex)
{
string aa = Convert.ToString(ex.Data["Exception"]);
throw ex;
}
I don't know what I am missing here. But aa seems to be always empty and ex.Data.Count is always zero.
I just want to pass one code between two applications without adding new class of an exception.
Note: These two applications are wcf calls.
[EDIT1]
Application 1 validate request is the IDispatchMessageInspector AfterReceiveRequest
Exceptions are not propagated to clients from a WCF service. Instead, a SOAP Fault (assuming you are using SOAP) will be sent to the client.
You can include exception details in the SOAP Fault, but in general it is not recommended to do so in production.
IMHO a better approach is to implement an IErrorHandler that provides the Fault with whatever data you want to send to the client, and also gives you the opportunity to log the exception server-side.
You can then catch FaultException on the client and have access to the data added by your custom error handler.
The exception class is designed by one throw / catch pair. If you should add any additional information to a cached exception, use the inner exception feature by the rethrow technique:
catch (Exception ex)
{
ErrorHandling.WriteError(ex);
var newEx = new MyException("Additional message", ex) // wrap the original exception instance.
newEx.Data.Add("Exception", "test");
throw newEx;
}
After catching the wrapper exception you can find the original exception in the InnerException property. Another advantage that the original and wrapper exceptions contain their own stack trace so it is easier to find location of error source.

How to throw error code in Custom HTTP Module?

I am writing an authorization function in Custom HTTP Module.This is my code:
private bool CheckAuthorization(HttpContext context)
{
string auth = context.Request.Headers["Authorization"];
if (string.IsNullOrEmpty(auth) || auth != "123")
{
context.Response.StatusCode = -404;//HttpStatusCode.MethodNotAllowed;
context.Response.Write("404 Not allowed!");
//webOperationContext.OutgoingResponse.StatusCode = HttpStatusCode.MethodNotAllowed;
}
return true;
}
My develop enviroment is:C# + .NET Framwork 4.0 + Visual Studio 2013 + WCF.My purpose is: When checked authorization failed,the request should not invoke the WCF method,and return a 404 method not allowed error.It is still invoke WCF method right now through return the error tips.Thank you!
You can throw an HttpException which will not be handled and supply the necessary error to the browser.
throw new HttpException(404, "HTTP/1.1 404 Unauthorized");
Throwing an exception will cause the request to terminate and your WCF method should not run. However, if you have a try catch wrapping the CheckAuthorization call, then it's important that you rethrow the HttpException. In order for it to work you cannot handle the exception, let the ASP.Net pipeline handle it.

Capturing SOAP faults and handling exceptions

I am consuming a web services. Some methods throw exception when i invoked, because the parameters are invalid values, for example. I want to handle the exceptions but it don't contains any data information, only the message "Bad Request". This is my http response:
try
{
var data = client.SomeMethod(4);
}
catch (Exception exception)
{
// exception.Message = Bad Request
// exception don't contains any more data information
}
How can I capture the other information
You can catch the exception with FaultException when the http status code is 2xx or 5xx, not 4xx. You can catch the http status code 4xx with System.ServiceModel.ProtocolException and then get the stream from the InnerException and parse it or get the FaultException from this stream. See http://blogs.msdn.com/b/nathana/archive/2011/03/31/deciphering-a-soap-fault-with-a-400-status-code.aspx for more details.
I'm assuming this is a WCF web service? You are catching to wide of an exception. Try with a FaultException<TDetail>.
Typical deployed services use the FaultContractAttribute to formally specify all SOAP faults that a client can expect to receive in the normal course of an operation. Error information in a FaultContractAttribute appears as a FaultException (where the typeparameter is the serializable error object specified in the operation's FaultContractAttribute) when it arrives at a client application. The FaultContractAttribute can be used to specify SOAP faults for both two-way service methods and for asynchronous method pairs.
Because FaultException is both a FaultException and therefore a CommunicationException, to catch specified SOAP faults make sure you catch the FaultException types prior to the FaultException and CommunicationException types or handle the specified exceptions in one of those exception handlers.
You can use try-catch like below. Then you can access other information. You have to find the "TDetail". It provides by the web service.
catch(FaultException<TDetail> ex)
{
ex.Code.ToString();
ex.Reason.ToString();
}
Other way.
FaultException faultException = (FaultException)ex;
MessageFault msgFault = faultException.CreateMessageFault();
XmlElement elm = msgFault.GetDetail<XmlElement>();

Exception handling in ASP.NET (C#) web services

I was looking for a way to transfer the exception message in web services of my asp.net application to the ajax error callback function.
All I could find was catching an exception thrown from web service into a C# code but i am calling my service from ajax code and not a C# code. I want something more than the HTTP status codes returned.
Here is catch block of my Service code:
catch (Exception ex)
{
var fault = new GenericFault { Message = ex.Message, Operation = "" };
throw new FaultException<GenericFault>(fault);
}
}
And here is my ajax error callback:
error: function (err) {
alert("The server encountered an error, please resubmit your request. If the problem persists, contact your administrator.");
return 'error occured';
}
I have already tried throwing web fault exception but that also didn't serve the purpose as only the HTTP status code gets passed.
Found an answer. The trick lies in throwing right exception.
As the error caught in the callback error function sees the details in xhr object.
So you need to throw the HttpException passing with it status code and string message.
catch block should look something like:
catch (Exception ex)
{
throw new HttpException(500, ex.Message);
}
then your ajax callback will get the ex.message that you are passing from here:
error: function (err) {
alert("The Detailed server error is "+err.responseJSON.Message);
return 'error occured';
}

How to handle a exception thrown in c# by a javascript web app?

I'm developing a web application with a client side build with html5 and javascript using, overall, dojo framework (I'm using xhr.post function to communicate with server). The server side is an asmx service in c#.
Here comes the problem: when a webmethod of my service throws an exception:
try
{
throw new Exception("TEST");
}
catch (Exception ex)
{
throw ex;
// TODO: send some info to the client about the error
}
the client is realized than an error has occured and fires the error callback function:
deferred = xhr.post({
url: that.config.urlService,
handleAs: that.config.handleAs,
contentType: that.config.contentType,
postData: that.config.parameters
});
deferred.then(function (res) {
that.success(res);
},
function (err) {
if (that.config.callbackFail) {
that.config.callbackFail(err, that.config.parameters);
}
}
);
But in the 'err' paramater I don't have the exception info, I have the message:
'NetworkError: 500 Internal Server Error - http:/.../Services/Applications/Metrawa/ServiceManagement/WSJob.asmx/Filter'
and inspecting the call to server with firebug, in the response tab I can see strange characters, like if the exception hasn't been serialized.
What I want is to get the exception info in javascript. I've searched some info about this, like to create an own serializable exception class, but it doesn´t work neither. Any solution?
Thanks in advance.
You may opt to handle the exception in your server-side code and send it back as JSON, XML or even String--i.e. something your client can understand.
I would catch the exception server side and always return a valid object with a "Result" property:
eg res.Result (as "OK" or "ERR" etc and handle that on the client)

Categories