Created
December 13, 2013 11:55
-
-
Save mahizsas/7943240 to your computer and use it in GitHub Desktop.
From http://weblog.west-wind.com/posts/2013/Dec/13/Accepting-Raw-Request-Body-Content-with-ASPNET-Web-API
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// Reads the Request body into a string/byte[] and | |
/// assigns it to the parameter bound. | |
/// | |
/// Should only be used with a single parameter on | |
/// a Web API method using the [NakedBody] attribute | |
/// </summary> | |
public class NakedBodyParameterBinding : HttpParameterBinding | |
{ | |
public NakedBodyParameterBinding(HttpParameterDescriptor descriptor) | |
: base(descriptor) | |
{ | |
} | |
public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, | |
HttpActionContext actionContext, | |
CancellationToken cancellationToken) | |
{ | |
var binding = actionContext | |
.ActionDescriptor | |
.ActionBinding; | |
if (binding.ParameterBindings.Length > 1 || | |
actionContext.Request.Method == HttpMethod.Get) | |
return EmptyTask.Start(); | |
var type = binding | |
.ParameterBindings[0] | |
.Descriptor.ParameterType; | |
if (type == typeof(string)) | |
{ | |
return actionContext.Request.Content | |
.ReadAsStringAsync() | |
.ContinueWith((task) => | |
{ | |
var stringResult = task.Result; | |
SetValue(actionContext, stringResult); | |
}); | |
} | |
else if (type == typeof(byte[])) | |
{ | |
return actionContext.Request.Content | |
.ReadAsByteArrayAsync() | |
.ContinueWith((task) => | |
{ | |
byte[] result = task.Result; | |
SetValue(actionContext, result); | |
}); | |
} | |
throw new InvalidOperationException("Only string and byte[] are supported for [NakedBody] parameters"); | |
} | |
public override bool WillReadBody | |
{ | |
get | |
{ | |
return true; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment