C#HTTP状态代码范围.NET 3.5
本文关键字:NET 范围 状态 代码 C#HTTP | 更新日期: 2023-09-27 18:26:23
我正在使用一个分析API,它在3个状态代码中响应:
200: Successfully ingested
400: Missing Parameter
50x: Server Error
我想将这些状态封装在一个可读的枚举中,但处理50x需要一系列枚举不支持的值。
关于如何应对这种情况,有什么建议吗?
虽然我无法找到直接支持特定枚举的一系列值的方法,但我确实提出了一个可能的解决方案。
一种扩展方法,可以用来解析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());
}
}
}
}