Dion
Dion

Reputation: 954

Serialization error when getting error response

I'm getting an error and can't figure out what I'm doing wrong:

"Type definitions should start with a '{', expecting serialized type 'MessageHistoryResponse', got string starting with: 
<!DOCTYPE html>
<html>
<head>
    <meta name=" ...

The client code is simpy:

var client = new JsonServiceClient(Url);

try
{
    var messageHistoryResponse = client.Send(new MessageHistory {
        Take = 20,
        Skip = 0
    });
}
catch (WebServiceException e)
{
    Console.WriteLine(e);
}

I have a request filter in place as follows:

public override void Execute(IRequest req, IResponse res, object requestDto)
{
    var token = req.Headers["authtoken"];

    if (token != null)
    {
        //Authenticated code
    }

    if (_logger.IsDebugEnabled)
        _logger.DebugFormat("[Token {0}] Access Denied", token);

    res.ReturnAuthRequired();
}

This is following one of the examples but instead of receiving a WebException,it throws a Serialization exception. I'm not sure how best to handle this?

All of my services use a standard requestDto/responseDto pattern. From the docs I was expecting a WebException to be thrown, which I could then handle. But instead it's a SerializationException and doesn't report that the Auth failed.

Anyone got any ideas to help me?

Upvotes: 0

Views: 1091

Answers (2)

Dion
Dion

Reputation: 954

I've managed to find the answer with help from the forums. The problem I was experiencing was due to a conflict between the ASP .NET membership provider and ServiceStack. When a 401 Unauthorised response was received, ASP .NET hijacks the request and takes over.

I changed my code to instead return a 403 Forbidden and I was back in business.

So frustrating but I'm glad we were able to get to the bottom of it in the end.

Thanks for your help.

Upvotes: 1

Scott
Scott

Reputation: 21501

Your filter hasn't set the content type to be application/json so the unauthorised error is being output as html which the JsonServiceClient doesn't expect.

You can set the response type and then throw the error

public override void Execute(IRequest req, IResponse res, object requestDto)
{
    ...
    res.ContentType = "application/json";
    throw new HttpError(System.Net.HttpStatusCode.Unauthorized, "401", "Invalid token, access denied");
}

Upvotes: 2

Related Questions