Search code examples
c#jqueryasp.netwcfhttp-redirect

WCF service redirect


I am using a WCF Service (Ajax enabled). In my service, when an error occurs, I am logging it in a DB and I am redirecting the user to an error page.

To redirect the user, I am using this :

HttpContext.Current.Response.Redirect("error.aspx");

So I am logging the error and redirecting the user

The thing is, when an error occurs, it is logged multiple time and the user is not redirected.

When I say it is logged multiple time, it means : I have multiple error record in my DB for this error. (Only suppose to have one log for one error)

So I tried to understand : Why ?

It look like when I try to redirect, the service method's begin again (like it is called again).

Here's my complete process :

I call the service with jquery :

$.getJSON("ContactService.svc/getsubtitle", { titleid: titleid }, function (data) {
       ...
});

Here's the service method :

[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Json)]
public void getsubtitle(string titleid)
{

    try
    {
        .... (ERROR !)   

    }
    catch (Exception ex)
    {
        LogTheError(ex);
        HttpContext.Current.Response.Redirect("error.aspx");
    }
}

So, can you guys help me to understand why the HttpContext.Current.Response.Redirect does not redirect and does a strange thing?


Solution

  • A web service is supposed to be consumed by machines, not humans, so there is no sense in a web service showing an error page.

    Also, a WCF service should be transport-agnostic, as it can use other transport channels than http, such as tcp, named pipes and more. You're assuming that there is an HttpContext and a client which will understand what is HTTP-302 status code, which is what will be sent to the client after a Response.Redirect call. This is wrong, you should not assume that your consumer will be a particular kind of software or have certain capabilities, as been a web browser.

    Instead, create a POCO class, declare it as a FaultContract attribute and return the error response in there. This will be useful to service consumers and not an html page.

    See this article about how to implement fault contract handling in WCF:

    http://www.codeproject.com/Articles/376303/Fault-Contract-Handling-Errors-in-WCF-and-A-Very-S