[英]C# HTTP Status Code Ranges .NET 3.5
I'm working with an analytics API that responds in 3 status codes: 我正在使用以3个状态代码响应的Analytics API:
200: Successfully ingested
400: Missing Parameter
50x: Server Error
I would like to encapsulate these statuses within a readable enum, but handling the 50x would require a range of values of which enums do not support. 我想将这些状态封装在可读的枚举中,但是处理50x会需要枚举不支持的一系列值。
Any suggestions on how to deal with this kind of scenario? 关于如何处理这种情况有什么建议吗?
While I wasn't able to find a way to directly support a range of values for a specific enum I did come up with a possible solution. 虽然我无法找到一种方法来直接支持特定枚举的一系列值,但我确实提出了一种可能的解决方案。
An extension method you can use to parse all codes between 500 and 599 and return a single AllServerErrors value. 您可以使用一种扩展方法来解析500到599之间的所有代码,并返回一个AllServerErrors值。
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace UnitTestProject35
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestSuccessParse()
{
HttpResponseCode parsedHttpCode = HttpResponseCode.Unknown;
parsedHttpCode.TryParse(200, out parsedHttpCode);
Assert.AreEqual(parsedHttpCode, HttpResponseCode.Success);
}
[TestMethod]
public void TestServerErrorParse()
{
HttpResponseCode parsedHttpCode = HttpResponseCode.Unknown;
parsedHttpCode.TryParse(500, out parsedHttpCode);
Assert.AreEqual(parsedHttpCode, HttpResponseCode.AllServerErrors);
}
}
public enum HttpResponseCode
{
Unknown = 0,
Success = 200,
MissingParameter = 400,
//etc...
AllServerErrors = -1,
InternalServerError = 500,
NotImplemented = 501,
BadGateway = 502,
//etc..
}
public static class EnumExtensions
{
public static void TryParse(this HttpResponseCode theEnum, int code, out HttpResponseCode result)
{
if (code >= 500 && code <= 599)
{
result = HttpResponseCode.AllServerErrors;
}
else
{
result = (HttpResponseCode)Enum.Parse(typeof(HttpResponseCode), code.ToString());
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.