0

I am writing an authorization function in Custom HTTP Module.This is my code:

        private bool CheckAuthorization(HttpContext context)
        {
            string auth = context.Request.Headers["Authorization"];            
            if (string.IsNullOrEmpty(auth) || auth != "123")
            {                    
                context.Response.StatusCode = -404;//HttpStatusCode.MethodNotAllowed;                
                context.Response.Write("404 Not allowed!");
                //webOperationContext.OutgoingResponse.StatusCode = HttpStatusCode.MethodNotAllowed;                
            }
            return true;
        }

My develop enviroment is:C# + .NET Framwork 4.0 + Visual Studio 2013 + WCF.My purpose is: When checked authorization failed,the request should not invoke the WCF method,and return a 404 method not allowed error.It is still invoke WCF method right now through return the error tips.Thank you!

1
  • 404 is Not Found, the closest you get is 405 Method Now Allowed but when it's about authorization a 401 Unauthorized or 403 Forbidden would be more correct. en.wikipedia.org/wiki/… Commented Aug 9, 2015 at 6:27

1 Answer 1

5

You can throw an HttpException which will not be handled and supply the necessary error to the browser.

throw new HttpException(404, "HTTP/1.1 404 Unauthorized");

Throwing an exception will cause the request to terminate and your WCF method should not run. However, if you have a try catch wrapping the CheckAuthorization call, then it's important that you rethrow the HttpException. In order for it to work you cannot handle the exception, let the ASP.Net pipeline handle it.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.