在C#中,我有枚举数据类型:
public enum DebugLevel
{
NONE = 0,
ERROR = 1,
...
}
在对象内:
public class DataOptions
{
#region Fields
public DebugLevel debug = DebugLevel.NONE;
...
并且数据通过POST在FormData中作为int:
提供Form Data:
debug: 0
然后在WebAPI中解析,如下所示:
[HttpPost]
public AjaxAnswer<SomeDataType[]> MyEndpoint(HttpRequestMessage req) {
DataOptions o = null;
try
{
o = req.DecodeJSON<DataOptions>();
}
catch (Newtonsoft.Json.JsonReaderException) // Not JSON - old frontend versions are sending as form data
{
try {
o = req.DecodeFormData<DataOptions>();
} catch(Exception e) {
return new AjaxAnswer<SomeDataType[]>() {success:false, data:new SomeDataType[0], Error: "Error in MyEndpoint", ErrorMessage: "Could not decode request payload: " + e.Message
}
}
DecodeFormData是一个自定义的扩展方法,如下所示:
public static T DecodeFormData<T>(this System.Net.Http.HttpRequestMessage req) where T : new()
{
string postdata = req.Content.ReadAsStringAsync().Result;
Dictionary<string, string> s = postdata.Split('&').Where(x=>x.Contains('=')).Select(x => x.Split('=')).ToDictionary(x => x[0], x => HttpContext.Current.Server.UrlDecode(x[1]));
return s.ToType<T>();
}
由于某种原因,此代码抛出错误:
从'System.String'到'MyNamespace.DebugLevel'
的无效演员表
没有enum
的转化没有成功。那里发生了什么(s.ToType<T>()
行后面)以及为什么?