How to terminate a request in the middle of service operation?

Topics: Web Api
May 3, 2011 at 10:33 PM

If I have following service:

    [ServiceContract]
    public class PaymentTransactionResource
    {
        [WebInvoke(UriTemplate = "/purchaseExample", Method = "GET")]
        public PurchaseInformation Get(HttpRequestMessage req)
        {
            HttpResponseMessage resp = new HttpResponseMessage();

            if (!req.Headers.TryGetValues("MY-SESSION_ID", out list))
            {
                resp.StatusCode = System.Net.HttpStatusCode.BadRequest;
                return null;
            }

            PurchaseInformation info = new PurchaseInformation()
            {
                 Amount = 50.0, AmountDeviationPercent = 10, AmountType = PaymentAmountType.Restaurant,
                 PurchasedItems = new PurchasedItem[1]
            };

            info.PurchasedItems[0] = new PurchasedItem()
            {
                 PurchasedItemId = 1, ItemType = "Bath", Name = "Soap", Price = 2.00
            };

            return info;
        }

The bold font indicates where I would like to terminate the request. What are my options? Can do I it in the pipeline? If so, how? Can I do it here? If so, how? I am looking for all options how I can do this.

Thanks.

Coordinator
May 3, 2011 at 11:44 PM

throw new HttpResponseException(resp);

That will make your response the response and immediately exit.

You can also stop processing outside the operation in the pipeline using operation handlers. For example imagine a handler that uses DataAnnotations to do validation.

Glenn