简体   繁体   中英

Throwing a fault inside a behavior and returning it to client

I'm writing some services in WCF to be called by a Silverlight client. I change status code to 200 every time a fault is to be returned, via a IDispatchMessageInspector.

It works almost perfect, but sometimes it keeps returning error 500: NotFound.

I have just written another IDispatchMessageInspector to commit changes in a ObjectContext. But when this fails, the error handler is not called.

I think by the time UnitOfWorkMessageInspector runs, the message was already been set up as a non-fault-response. How can I do both things work?

    public class UnitOfWorkMessageInspector : IDispatchMessageInspector
    {
        public void BeforeSendReply(ref Message reply, object correlationState)
        {
            if (!reply.IsFault)
            {
                try
                {
                    UnitOfWorkBase.Commit();
                }
                catch (OptimisticConcurrencyException)
                {
                    throw new FaultException("It was changed by another user. Try again.");
                }
            }
        }

Code 500 is Internal Error.

Some error is occuring and it is not caught on the server side.

In your code you only catch OptimisticConcurrencyException you need to also catch Exception.

I managed to make it work. I figured out my IDispatchMessageInspector for switching from status code 500 to 200 wouldn't work because the message was already built, then I replaced the message.

    public class UnitOfWorkMessageInspector : IDispatchMessageInspector
    {
        public void BeforeSendReply(ref Message reply, object correlationState)
        {
            if (!reply.IsFault)
            {
                try
                {
                    UnitOfWorkBase.Commit();
                }
                catch (OptimisticConcurrencyException)
                {
                    FaultException fe = new FaultException("It was changed by another user. Try again.");
                    reply = Message.CreateMessage(reply.Version, fe.CreateMessageFault(), fe.Action);
                }
            }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM