Web API - ProtoBufFormatter - return serializable 401 with custom Authorize attribute

271 Views Asked by At

Our problem is following: we are using the ProtoBufFormatter in our Web API.

config.Formatters.Add(new ProtoBufFormatter());

Also using our custom Authorize attribute. The problem is when our Web API is returning 401. Which results in Protobuf throwing and exception as it can't serialize the response, so it throws following exception:

No serializer defined for type: System.Object

When I comment out:

protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
        {
            // base.HandleUnauthorizedRequest(actionContext);
        }

the server stops throwing the exception as this prevents it to send the 401 response.

But I am not sure how to deal the best with this issue.

Should I then in my controller actions return a protobuf serializable response that contains that user is unauthorized?

1

There are 1 best solutions below

0
On BEST ANSWER

Solved by returning our serializable content in the response as following:

protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
        {
            actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized,
                new ApiResponse(false, ApiErrorMessages.Unauthorized, ErrorType.Unauthorized));
        }