OperationHandler SelectHandler(HttpContext httpContext, IOperationCoordinator coorinator, out AcceptVerbs verb, out string ext)
{
// out default
verb = AcceptVerbs.Get;
ext = "";
var path = httpContext.Request.Path.Value;
var method = httpContext.Request.Method;
// extract path
var keyBase = path.Trim('/').Split('/');
if (keyBase.Length != 2)
{
goto NOT_FOUND;
}
// extract "extension" for media type
var extStart = keyBase[1].LastIndexOf(".");
if (extStart != -1)
{
ext = keyBase[1].Substring(extStart + 1);
keyBase[1] = keyBase[1].Substring(0, keyBase[1].Length - ext.Length - 1);
}
// {ClassName, MethodName}
var key = new RequestPath(keyBase[0], keyBase[1]);
OperationHandler handler;
if (handlers.TryGetValue(key, out handler))
{
// verb check
if (StringComparer.OrdinalIgnoreCase.Equals(method, "GET"))
{
verb = AcceptVerbs.Get;
}
else if (StringComparer.OrdinalIgnoreCase.Equals(method, "POST"))
{
verb = AcceptVerbs.Post;
}
else if (StringComparer.OrdinalIgnoreCase.Equals(method, "PUT"))
{
verb = AcceptVerbs.Put;
}
else if (StringComparer.OrdinalIgnoreCase.Equals(method, "DELETE"))
{
verb = AcceptVerbs.Delete;
}
else if (StringComparer.OrdinalIgnoreCase.Equals(method, "PATCH"))
{
verb = AcceptVerbs.Patch;
}
else
{
goto VERB_MISSING;
}
if (!handler.AcceptVerb.HasFlag(verb))
{
goto VERB_MISSING;
}
return handler; // OK
}
else
{
goto NOT_FOUND;
}
VERB_MISSING:
coorinator.OnProcessInterrupt(options, httpContext, InterruptReason.MethodNotAllowed, "MethodName:" + method);
options.Logger.MethodNotAllowed(OperationMissingKind.MethodNotAllowed, path, method);
if (options.OperationMissingHandlingPolicy == OperationMissingHandlingPolicy.ThrowException)
{
throw new MethodNotAllowedException(OperationMissingKind.MethodNotAllowed, path, method);
}
else
{
httpContext.EmitMethodNotAllowed();
if (options.OperationMissingHandlingPolicy == OperationMissingHandlingPolicy.ReturnErrorStatusCodeIncludeErrorDetails)
{
httpContext.EmitStringMessage("MethodNotAllowed:" + method);
}
return null;
}
NOT_FOUND:
coorinator.OnProcessInterrupt(options, httpContext, InterruptReason.OperationNotFound, "SearchedPath:" + path);
options.Logger.OperationNotFound(OperationMissingKind.OperationNotFound, path);
if (options.OperationMissingHandlingPolicy == OperationMissingHandlingPolicy.ThrowException)
{
throw new OperationNotFoundException(OperationMissingKind.MethodNotAllowed, path);
}
else
{
httpContext.EmitNotFound();
if (options.OperationMissingHandlingPolicy == OperationMissingHandlingPolicy.ReturnErrorStatusCodeIncludeErrorDetails)
{
httpContext.EmitStringMessage("OperationNotFound:" + path);
}
return null;
}
}