Thursday, May 19, 2011

ODATA Custom Exceptions

http://msdn.microsoft.com/en-us/library/ee391967.aspx#Y1700
   1:  public class AuthenticationInterceptor : RequestInterceptor
   2:  {
   3:      public AuthenticationInterceptor() : base(false) { }
   4:      public override void ProcessRequest(ref RequestContext requestContext)
   5:      {
   6:          if (!IsValidApiKey(requestContext))
   7:              GenerateErrorResponse(requestContext,
   8:                  HttpStatusCode.Unauthorized,
   9:                  "Missing or invalid user key (supply via the Authorization header)");
  10:      }
  11:      public bool IsValidUserKey(Message req, string key, string uri)
  12:      {
  13:          ... // ommitted for brevity
  14:      }
  15:      public void GenerateErrorResponse(RequestContext requestContext,
  16:          HttpStatusCode statusCode, string errorMessage)
  17:      {
  18:          // The error message is padded so that IE shows the response by default
  19:          string errorHtml =
  20:              "<html><HEAD><TITLE>Request Error</TITLE></HEAD><BODY>" +
  21:              "<H1>Error processing request</H1><P>{0}</P></BODY></html>";
  22:          XElement response = XElement.Load(new StringReader(
  23:              string.Format(errorHtml, errorMessage)));
  24:          Message reply = Message.CreateMessage(MessageVersion.None, null, response);
  25:          HttpResponseMessageProperty responseProp = new HttpResponseMessageProperty()
  26:          {
  27:              StatusCode = statusCode
  28:          };
  29:          responseProp.Headers[HttpResponseHeader.ContentType] = "text/html";
  30:          reply.Properties[HttpResponseMessageProperty.Name] = responseProp;
  31:          requestContext.Reply(reply);
  32:          // set the request context to null to terminate processing of this request
  33:          requestContext = null;
  34:      }
  35:  }

No comments:

Post a Comment