What’s the currently recommended way of performing partial updates with Web API?

There is no support in the current latest stable release of Web API (from August 2012). So if all you want to use is Web API RTM, you would have to implement the whole plumbing yourself. With that said, OData prerelease package supports partial updates very nicely through the new Delta<T> object. Currently the Microsoft.AspNet.WebApi.OData … Read more

How to put conditional Required Attribute into class property to work with WEB API?

You can implement your own ValidationAttribute. Perhaps something like this: public class RequireWhenCategoryAttribute : ValidationAttribute { protected override ValidationResult IsValid(object value, ValidationContext validationContext) { var employee = (EmployeeModel) validationContext.ObjectInstance; if (employee.CategoryId == 1) return ValidationResult.Success; var emailStr = value as string; return string.IsNullOrWhiteSpace(emailStr) ? new ValidationResult(“Value is required.”) : ValidationResult.Success; } } public sealed class … Read more

Using HttpContext.Current in WebApi is dangerous because of async

HttpContext.Current gets the current context by Thread (I looked into the implementation directly). It would be more correct to say that HttpContext is applied to a thread; or a thread “enters” the HttpContext. Using HttpContext.Current inside of async Task is not possible, because it can run on another Thread. Not at all; the default behavior … Read more

Suppress properties with null value on ASP.NET Web API

In the WebApiConfig: config.Formatters.JsonFormatter.SerializerSettings = new JsonSerializerSettings {NullValueHandling = NullValueHandling.Ignore}; Or, if you want more control, you can replace entire formatter: var jsonformatter = new JsonMediaTypeFormatter { SerializerSettings = { NullValueHandling = NullValueHandling.Ignore } }; config.Formatters.RemoveAt(0); config.Formatters.Insert(0, jsonformatter);

ASP.NET Core v2 (2015) MVC : How to get raw JSON bound to a string without a type?

The cleanest option I’ve found is adding your own simple InputFormatter: public class RawJsonBodyInputFormatter : InputFormatter { public RawJsonBodyInputFormatter() { this.SupportedMediaTypes.Add(“application/json”); } public override async Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context) { var request = context.HttpContext.Request; using (var reader = new StreamReader(request.Body)) { var content = await reader.ReadToEndAsync(); return await InputFormatterResult.SuccessAsync(content); } } protected override bool CanReadType(Type type) … Read more