Ask Learn
Preview
Ask Learn is an AI assistant that can answer questions, clarify concepts, and define terms using trusted Microsoft documentation.
Please sign in to use Ask Learn.
Sign inThis browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Quick post today. MVC developers are used to the [RequireHttps] attribute, which is an authorization filter which doesn’t allow any requests to be made over "plain” HTTP. This attribute doesn’t exist in Web API, but it’s fairly simple to replicate the same behavior using an authorization filter (an action filter would work just as well, but since the MVC attribute is an IAuthorizationFilter, we did the same here). By having it as an attribute we can simply apply it to any controller or action, and all requests to that controller (or action) will pass through this attribute.
The logic is simple – if the request comes via HTTPS, nothing happens. If it doesn’t, then there are two possible alternatives: if the request verb is GET (or HEAD), then the filter bypasses the operation, and responds to the request with a redirect response, and most HTTP stacks will resend the request to the location specified. If the request verb is not GET (or HEAD) , then we could also return a redirect response, but the problem is that many of the HTTP stacks (I don’t know if all of them, but I tried quite a few) issue a GET request in response to a Redirect from non-GET requests (since per the HTTP RFC they cannot send a non-GET request after redirecting without user confirmation), so that’s not what we want. In this case, we simply return an error response instead.
That’s it. The behavior is almost identical to the MVC [RequireHttps] attribute, except that for non-GET requests the MVC attribute returns a 500 (Internal Server Error) response, while this implementation returns a 404 (Not Found) – thanks to @pmhsfelix for the insight on this.
Ask Learn is an AI assistant that can answer questions, clarify concepts, and define terms using trusted Microsoft documentation.
Please sign in to use Ask Learn.
Sign in