Refactor ToHttpMethod to use a dictionary for mappings
Replaced the switch statement in the ToHttpMethod method with a case-insensitive dictionary for mapping HTTP method strings to HttpMethod objects. Introduced a private static dictionary to store predefined HTTP methods, including the addition of the CONNECT method. Improved performance and maintainability by leveraging dictionary lookups for faster and cleaner code.
This commit is contained in:
parent
bbfff226de
commit
21e3171e11
@ -2,16 +2,20 @@
|
|||||||
|
|
||||||
public static class HttpExtensions
|
public static class HttpExtensions
|
||||||
{
|
{
|
||||||
public static HttpMethod ToHttpMethod(this string method) => method.ToUpper() switch
|
private static readonly Dictionary<string, HttpMethod> _methods = new(StringComparer.OrdinalIgnoreCase)
|
||||||
{
|
{
|
||||||
"GET" => HttpMethod.Get,
|
["GET"] = HttpMethod.Get,
|
||||||
"POST" => HttpMethod.Post,
|
["POST"] = HttpMethod.Post,
|
||||||
"PUT" => HttpMethod.Put,
|
["PUT"] = HttpMethod.Put,
|
||||||
"DELETE" => HttpMethod.Delete,
|
["DELETE"] = HttpMethod.Delete,
|
||||||
"PATCH" => HttpMethod.Patch,
|
["PATCH"] = HttpMethod.Patch,
|
||||||
"HEAD" => HttpMethod.Head,
|
["HEAD"] = HttpMethod.Head,
|
||||||
"OPTIONS" => HttpMethod.Options,
|
["OPTIONS"] = HttpMethod.Options,
|
||||||
"TRACE" => HttpMethod.Trace,
|
["TRACE"] = HttpMethod.Trace,
|
||||||
_ => throw new ArgumentException($"Invalid HTTP method: {method}", nameof(method)),
|
["CONNECT"] = HttpMethod.Connect
|
||||||
};
|
};
|
||||||
|
|
||||||
|
public static HttpMethod ToHttpMethod(this string method) => _methods.TryGetValue(method, out var httpMethod)
|
||||||
|
? httpMethod
|
||||||
|
: new HttpMethod(method);
|
||||||
}
|
}
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user