webapi httpcontent怎么实例化
发布网友
发布时间:2022-05-15 20:31
我来回答
共1个回答
热心网友
时间:2024-02-27 17:20
public class ValueProvider : IValueProvider
{
private IEnumerable<KeyValuePair<string, string>> _queryParameters;
private HttpContent _httpContent;
private HttpActionContext _context;
public ValueProvider(HttpActionContext context)
{
_context = context;
_httpContent = context.Request.Content;
_queryParameters = context.Request.GetQueryNameValuePairs();
}
public bool ContainsPrefix(string prefix)
{
return _queryParameters.Any(x => x.Key == prefix);
}
NameValueCollection _formDatas = (NameValueCollection)CallContext.LogicalGetData("$formDatas");
public ValueProviderResult GetValue(string key)
{
var value = _queryParameters.FirstOrDefault(x => x.Key == key).Value;
if (string.IsNullOrWhiteSpace(value))
{
if (_formDatas == null)
{
if (_httpContent.IsFormData())
{
if (_formDatas == null)
{
_formDatas = _httpContent.ReadAsFormDataAsync().Result;
CallContext.LogicalSetData("$formDatas", _formDatas);
}
}
else
{
throw new HttpResponseException(_context.Request.CreateErrorResponse(System.Net.HttpStatusCode.NotFound, string.Format("未在URL中找到名为{0}的参数,此时必须传入表单参数或json或xml参数", key)));
}
}
value = _formDatas[key];
if (string.IsNullOrWhiteSpace(value))
{
throw new HttpResponseException(_context.Request.CreateErrorResponse(System.Net.HttpStatusCode.NotFound, string.Format("未在URL中找到名为{0}的参数,也未在表单中找到该参数", key)));
}
}
return new ValueProviderResult(value, value, CultureInfo.InvariantCulture);
}
}