本文整理汇总了C#中InputFormatterContext类的典型用法代码示例。如果您正苦于以下问题:C# InputFormatterContext类的具体用法?C# InputFormatterContext怎么用?C# InputFormatterContext使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
InputFormatterContext类属于命名空间,在下文中一共展示了InputFormatterContext类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: JsonPatchInputFormatter_ReadsOneOperation_Successfully
public async Task JsonPatchInputFormatter_ReadsOneOperation_Successfully()
{
// Arrange
var formatter = new JsonPatchInputFormatter();
var content = "[{\"op\":\"add\",\"path\":\"Customer/Name\",\"value\":\"John\"}]";
var contentBytes = Encoding.UTF8.GetBytes(content);
var modelState = new ModelStateDictionary();
var httpContext = GetHttpContext(contentBytes);
var context = new InputFormatterContext(
httpContext,
modelName: string.Empty,
modelState: modelState,
modelType: typeof(JsonPatchDocument<Customer>));
// Act
var result = await formatter.ReadAsync(context);
// Assert
Assert.False(result.HasError);
var patchDoc = Assert.IsType<JsonPatchDocument<Customer>>(result.Model);
Assert.Equal("add", patchDoc.Operations[0].op);
Assert.Equal("Customer/Name", patchDoc.Operations[0].path);
Assert.Equal("John", patchDoc.Operations[0].value);
}
示例2: JsonPatchInputFormatter_ReadsMultipleOperations_Successfully
public async Task JsonPatchInputFormatter_ReadsMultipleOperations_Successfully()
{
// Arrange
var logger = GetLogger();
var formatter = new JsonPatchInputFormatter(logger);
var content = "[{\"op\": \"add\", \"path\" : \"Customer/Name\", \"value\":\"John\"}," +
"{\"op\": \"remove\", \"path\" : \"Customer/Name\"}]";
var contentBytes = Encoding.UTF8.GetBytes(content);
var modelState = new ModelStateDictionary();
var httpContext = GetHttpContext(contentBytes);
var provider = new EmptyModelMetadataProvider();
var metadata = provider.GetMetadataForType(typeof(JsonPatchDocument<Customer>));
var context = new InputFormatterContext(
httpContext,
modelName: string.Empty,
modelState: modelState,
metadata: metadata,
readerFactory: new TestHttpRequestStreamReaderFactory().CreateReader);
// Act
var result = await formatter.ReadAsync(context);
// Assert
Assert.False(result.HasError);
var patchDoc = Assert.IsType<JsonPatchDocument<Customer>>(result.Model);
Assert.Equal("add", patchDoc.Operations[0].op);
Assert.Equal("Customer/Name", patchDoc.Operations[0].path);
Assert.Equal("John", patchDoc.Operations[0].value);
Assert.Equal("remove", patchDoc.Operations[1].op);
Assert.Equal("Customer/Name", patchDoc.Operations[1].path);
}
示例3: ReadAsync
public Task<InputFormatterResult> ReadAsync(InputFormatterContext context)
{
if (context == null)
throw new ArgumentNullException(nameof(context));
var request = context.HttpContext.Request;
if (request.ContentLength == 0)
{
return InputFormatterResult.SuccessAsync(null);
}
try
{
var model = DeSerializationService.DeserializeFromRoot(GetRequestBody(context.HttpContext.Request.Body),
_inputFormatterOptions);
return InputFormatterResult.SuccessAsync(model);
}
catch (JsonSerializationException)
{
context.HttpContext.Response.StatusCode = 422;
return InputFormatterResult.FailureAsync();
}
}
示例4: ReadRequestBodyAsync
/// <summary>
/// Reads the input XML.
/// </summary>
/// <param name="context">The input formatter context which contains the body to be read.</param>
/// <returns>Task which reads the input.</returns>
public override Task<object> ReadRequestBodyAsync(InputFormatterContext context)
{
var request = context.ActionContext.HttpContext.Request;
MediaTypeHeaderValue requestContentType;
MediaTypeHeaderValue.TryParse(request.ContentType, out requestContentType);
var effectiveEncoding = SelectCharacterEncoding(requestContentType);
using (var xmlReader = CreateXmlReader(new NonDisposableStream(request.Body), effectiveEncoding))
{
var type = GetSerializableType(context.ModelType);
var serializer = GetCachedSerializer(type);
var deserializedObject = serializer.Deserialize(xmlReader);
// Unwrap only if the original type was wrapped.
if (type != context.ModelType)
{
var unwrappable = deserializedObject as IUnwrappable;
if (unwrappable != null)
{
deserializedObject = unwrappable.Unwrap(declaredType: context.ModelType);
}
}
return Task.FromResult(deserializedObject);
}
}
示例5: CanRead_ReturnsTrueForAnySupportedContentType
public void CanRead_ReturnsTrueForAnySupportedContentType(string requestContentType, bool expectedCanRead)
{
// Arrange
var loggerMock = GetLogger();
var formatter =
new JsonInputFormatter(loggerMock, _serializerSettings, ArrayPool<char>.Shared, _objectPoolProvider);
var contentBytes = Encoding.UTF8.GetBytes("content");
var httpContext = GetHttpContext(contentBytes, contentType: requestContentType);
var provider = new EmptyModelMetadataProvider();
var metadata = provider.GetMetadataForType(typeof(string));
var formatterContext = new InputFormatterContext(
httpContext,
modelName: string.Empty,
modelState: new ModelStateDictionary(),
metadata: metadata,
readerFactory: new TestHttpRequestStreamReaderFactory().CreateReader);
// Act
var result = formatter.CanRead(formatterContext);
// Assert
Assert.Equal(expectedCanRead, result);
}
示例6: ReadRequestBodyAsync
public override Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context, Encoding encoding)
{
var request = context.HttpContext.Request;
using (var reader = new BsonReader(request.Body))
{
var successful = true;
EventHandler<ErrorEventArgs> errorHandler = (sender, eventArgs) =>
{
successful = false;
var exception = eventArgs.ErrorContext.Error;
eventArgs.ErrorContext.Handled = true;
};
var jsonSerializer = CreateJsonSerializer();
jsonSerializer.Error += errorHandler;
var type = context.ModelType;
object model;
try
{
model = jsonSerializer.Deserialize(reader, type);
}
finally
{
_jsonSerializerPool.Return(jsonSerializer);
}
if (successful)
{
return InputFormatterResult.SuccessAsync(model);
}
return InputFormatterResult.FailureAsync();
}
}
示例7: ReadAsync
public async Task<InputFormatterResult> ReadAsync(InputFormatterContext context)
{
using (var requestStream = new StreamReader(context.HttpContext.Request.Body, Encoding.UTF8))
{
var requestData = await requestStream.ReadToEndAsync();
return InputFormatterResult.Success(JsonConvert.DeserializeObject(requestData, context.ModelType, SerializerSettings));
}
}
示例8: CanRead
public override bool CanRead(InputFormatterContext context)
{
var type = context.ModelType;
if (type == null)
throw new ArgumentNullException("type");
return IsTypeOfIEnumerable(type);
}
示例9: BindModelCoreAsync
/// <summary>
/// Attempts to bind the model using formatters.
/// </summary>
/// <param name="bindingContext">The <see cref="ModelBindingContext"/>.</param>
/// <returns>
/// A <see cref="Task{ModelBindingResult}"/> which when completed returns a <see cref="ModelBindingResult"/>.
/// </returns>
private async Task<ModelBindingResult> BindModelCoreAsync([NotNull] ModelBindingContext bindingContext)
{
// For compatibility with MVC 5.0 for top level object we want to consider an empty key instead of
// the parameter name/a custom name. In all other cases (like when binding body to a property) we
// consider the entire ModelName as a prefix.
var modelBindingKey = bindingContext.IsTopLevelObject ? string.Empty : bindingContext.ModelName;
var httpContext = bindingContext.OperationBindingContext.HttpContext;
var formatterContext = new InputFormatterContext(
httpContext,
modelBindingKey,
bindingContext.ModelState,
bindingContext.ModelType);
var formatters = bindingContext.OperationBindingContext.InputFormatters;
var formatter = formatters.FirstOrDefault(f => f.CanRead(formatterContext));
if (formatter == null)
{
var unsupportedContentType = Resources.FormatUnsupportedContentType(
bindingContext.OperationBindingContext.HttpContext.Request.ContentType);
bindingContext.ModelState.AddModelError(modelBindingKey, unsupportedContentType);
// This model binder is the only handler for the Body binding source and it cannot run twice. Always
// tell the model binding system to skip other model binders and never to fall back i.e. indicate a
// fatal error.
return ModelBindingResult.Failed(modelBindingKey);
}
try
{
var previousCount = bindingContext.ModelState.ErrorCount;
var result = await formatter.ReadAsync(formatterContext);
var model = result.Model;
// Ensure a "modelBindingKey" entry exists whether or not formatting was successful.
bindingContext.ModelState.SetModelValue(modelBindingKey, rawValue: model, attemptedValue: null);
if (result.HasError)
{
// Formatter encountered an error. Do not use the model it returned. As above, tell the model
// binding system to skip other model binders and never to fall back.
return ModelBindingResult.Failed(modelBindingKey);
}
return ModelBindingResult.Success(modelBindingKey, model);
}
catch (Exception ex)
{
bindingContext.ModelState.AddModelError(modelBindingKey, ex);
// This model binder is the only handler for the Body binding source and it cannot run twice. Always
// tell the model binding system to skip other model binders and never to fall back i.e. indicate a
// fatal error.
return ModelBindingResult.Failed(modelBindingKey);
}
}
示例10: ReadRequestBodyAsync
public override Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context, Encoding effectiveEncoding)
{
var request = context.HttpContext.Request;
using (var reader = new StreamReader(request.Body, effectiveEncoding))
{
var stringContent = reader.ReadToEnd();
return InputFormatterResult.SuccessAsync(stringContent);
}
}
示例11: CanRead
public bool CanRead(InputFormatterContext context)
{
if (context == null)
throw new ArgumentNullException(nameof(context));
var contentTypeString = context.HttpContext.Request.ContentType;
return string.IsNullOrEmpty(contentTypeString) || contentTypeString == "application/json";
}
示例12: ReadRequestBodyAsync
public override Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context)
{
var type = context.ModelType;
var request = context.HttpContext.Request;
MediaTypeHeaderValue requestContentType = null;
MediaTypeHeaderValue.TryParse(request.ContentType, out requestContentType);
var result = ReadStream(type, request.Body);
return InputFormatterResult.SuccessAsync(result);
}
示例13: ReadRequestBodyAsync
public override Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context, Encoding encoding)
{
var request = context.HttpContext.Request;
string value;
using (var reader = new StreamReader(request.Body))
{
value = reader.ReadToEnd();
}
return InputFormatterResult.SuccessAsync(value);
}
示例14: CanRead
public override bool CanRead(InputFormatterContext context)
{
bool result = false;
MediaTypeHeaderValue requestContentType;
if (this.CanReadType(context.ModelType) && MediaTypeHeaderValue.TryParse(context.HttpContext.Request.ContentType, out requestContentType))
{
if ((string.Compare(requestContentType.Type, "application", true) == 0) && requestContentType.SubType.EndsWith("+json", StringComparison.InvariantCultureIgnoreCase))
result = true;
else
result = base.CanRead(context);
}
return result;
}
示例15: JsonFormatterReadsSimpleTypes
public async Task JsonFormatterReadsSimpleTypes(string content, Type type, object expected)
{
// Arrange
var formatter = new JsonInputFormatter();
var contentBytes = Encoding.UTF8.GetBytes(content);
var actionContext = GetActionContext(contentBytes);
var context = new InputFormatterContext(actionContext, type);
// Act
var model = await formatter.ReadAsync(context);
// Assert
Assert.Equal(expected, model);
}