Jil.DeserializationException: 'Expected digit' - c#

I am trying to implement the Jil serializer in WebAPI(C#). While deserializing throws the error like "Jil.DeserializationException: 'Expected digit'". I have attached the code samples.
WebApiConfig.cs
config.Formatters.Clear();
var _jilOptions = new Options(dateFormat: DateTimeFormat.ISO8601, excludeNulls: true, includeInherited: true);
config.Formatters.Add(new JilFormatter(_jilOptions));
JilFormatter.cs
public class JilFormatter : MediaTypeFormatter
{
private static readonly MediaTypeHeaderValue _applicationJsonMediaType = new MediaTypeHeaderValue("application/json");
private static readonly MediaTypeHeaderValue _textJsonMediaType = new MediaTypeHeaderValue("text/json");
private readonly Options _options;
public JilFormatter(Options options)
{
_options = options;
SupportedMediaTypes.Add(_applicationJsonMediaType);
SupportedMediaTypes.Add(_textJsonMediaType);
SupportedEncodings.Add(new UTF8Encoding(false, true));
SupportedEncodings.Add(new UnicodeEncoding(false, true, true));
}
public override bool CanReadType(Type type)
{
if (type == null)
return false;
return true;
}
public override bool CanWriteType(Type type)
{
if (type == null)
return false;
return true;
}
public override Task<object> ReadFromStreamAsync(Type type, Stream input, HttpContent content, IFormatterLogger formatterLogger)
{
var reader = new StreamReader(input);
var deserialize = TypedDeserializers.GetTyped(type);
var result = deserialize(reader, _options);
return Task.FromResult(result);
}
public override Task WriteToStreamAsync(Type type, object value, Stream output, HttpContent content, TransportContext transportContext)
{
var writer = new StreamWriter(output);
JSON.Serialize(value, writer, _options);
writer.Flush();
return Task.FromResult(true);
}
}
TypedDeserializers class:
static class TypedDeserializers
{
private static readonly ConcurrentDictionary<Type, Func<TextReader, Options, object>> _methods;
private static readonly MethodInfo _method = typeof(JSON).GetMethod("Deserialize", new[] { typeof(TextReader), typeof(Options) });
static TypedDeserializers()
{
_methods = new ConcurrentDictionary<Type, Func<TextReader, Options, object>>();
}
public static Func<TextReader, Options, object> GetTyped(Type type)
{
return _methods.GetOrAdd(type, CreateDelegate);
}
private static Func<TextReader, Options, object> CreateDelegate(Type type)
{
return (Func<TextReader, Options, object>)_method
.MakeGenericMethod(type)
.CreateDelegate(typeof(Func<TextReader, Options, object>));
}
}
ReuestTest.cs
public class ReuestTest
{
public long UserId { get; set; }
public long MobileDeviceId { get; set; }
public bool IsInitialLoad { get; set; }
}
testController.cs
[HttpPost]
public string GetAllDispatchestest(ReuestTest request)
{
return something;
}
Exception:
{
"Message": "An error has occurred.",
"ExceptionMessage": "Expected digit",
"ExceptionType": "Jil.DeserializationException",
"StackTrace": " at Jil.Deserialize.Methods._ReadInt64(TextReader reader)\r\n at _DynamicMethod4(TextReader , Int32 )\r\n at Jil.JSON.Deserialize[T](TextReader reader, Options options)\r\n at api.myapi.com.Utilities.JilFormatter.ReadFromStreamAsync(Type type, Stream input, HttpContent content, IFormatterLogger formatterLogger) in F:\\Projects\\myapi\\myapi.Solution\\api.myapi.com\\Utilities\\JilFormatter.cs:line 51\r\n at System.Net.Http.Formatting.MediaTypeFormatter.ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger, CancellationToken cancellationToken)\r\n at System.Net.Http.HttpContentExtensions.<ReadAsAsyncCore>d__0`1.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.ModelBinding.FormatterParameterBinding.<ExecuteBindingAsyncCore>d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Controllers.HttpActionBinding.<ExecuteBindingAsyncCore>d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Controllers.ExceptionFilterResult.<ExecuteAsync>d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Web.Http.Controllers.ExceptionFilterResult.<ExecuteAsync>d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()"
}

Related

Error with IHttpActionResult in web api actions

I am facing method not found error in web server, but locally in visual studio it works:
[HttpGet]
[Route("api/checkhealth")]
public async Task<IHttpActionResult> CheckHealth()
{
var message = "checkhealth method was invoked";
return new TextResult(message, Request);
}
Then in browser getting below error:
<Error>
<Message>An error has occurred.</Message>
<ExceptionMessage>Method not found: 'System.Net.Http.HttpRequestMessage System.Web.Http.ApiController.get_Request()'.
</ExceptionMessage>
<ExceptionType>System.MissingMethodException</ExceptionType>
<StackTrace>at BMI.Controllers.APIController.<CheckHealth>d__0.MoveNext() at System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.Start[TStateMachine](TStateMachine& stateMachine) at BMI.Controllers.APIController.CheckHealth() at lambda_method(Closure , Object , Object[] ) at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass6_3.<GetExecutor>b__2(Object instance, Object[] methodParameters) at
System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken) --- End of stack trace from previous location where exception was thrown --- at
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Web.Http.Controllers.ApiControllerActionInvoker.
<InvokeActionAsyncCore>d__1.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Web.Http.Controllers.ActionFilterResult.
<ExecuteAsync>d__5.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Web.Http.Dispatcher.HttpControllerDispatcher.
<SendAsync>d__15.MoveNext()
</StackTrace>
</Error>
I have implemented IHttpActionResult as below:
public class TextResult : IHttpActionResult
{
string message;
HttpRequestMessage request;
public TextResult(string message, HttpRequestMessage request)
{
this.message = message;
this.request = request;
}
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
var response = new HttpResponseMessage()
{
Content = new StringContent(message),
RequestMessage = request
};
return Task.FromResult(response);
}
}
The actual method in my project is post but here I am trying to fix with get first then I believe post will also work.
Here to mention the below method work perfectly, so I think something I am missing with IHttpActionResult:
[HttpGet]
[Route("api/getok")]
public JsonResult<string> getJson()
{
return Json("OK");
}
Do you have any one faced and solved this problem yet. Please help me, thanks in advance.
Using the CreateResponse extension on the request would allow any configuration from the request to be copied over to the response which would probably be missing when you create the response manually like in your example.
public class TextResult : IHttpActionResult {
string message;
HttpRequestMessage request;
public TextResult(string message, HttpRequestMessage request) {
this.message = message;
this.request = request;
}
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken) {
var response = request.CreateResponse(HttpStatusCode.OK, message);
return Task.FromResult(response);
}
}
Also the controller action is not defined correctly as it is defined as async Task<IHttpActionResult> when the action is not doing anything async.
Refactor to follow correct syntax if not actually asynchronous.
[HttpGet]
[Route("api/checkhealth")]
public IHttpActionResult CheckHealth() {
var message = "checkhealth method was invoked";
return new TextResult(message, Request);
}

InternalClientWebSocket instance cannot be used for communication because it has been transitioned into the 'Aborted' state

I have an exception when I try to receive data from more than three websockets. If I try on only one, two or three websockets it works perfectly.
I get the exception in this line:
tasks.Add(Send(webSocket, "11"));
The exception message:
Exception: System.Net.WebSockets.WebSocketException (0x80004005): The
'System.Net.WebSockets.InternalClientWebSocket' instance cannot be
used for communication because it has been transitioned into the
'Aborted' state. ---> System.OperationCanceledException: The operation
was canceled. at
System.Threading.CancellationToken.ThrowOperationCanceledException()
at
System.Net.WebSockets.WebSocketConnectionStream.d__21.MoveNext()
--- End of stack trace from previous location where exception was thrown --- at
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task) at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at
System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
at
System.Net.WebSockets.WebSocketBase.WebSocketOperation.d__19.MoveNext()
--- End of stack trace from previous location where exception was thrown --- at
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task) at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at
System.Net.WebSockets.WebSocketBase.d__45.MoveNext()
at System.Net.WebSockets.WebSocketBase.ThrowIfAborted(Boolean aborted,
Exception innerException) at
System.Net.WebSockets.WebSocketBase.ThrowIfConvertibleException(String
methodName, Exception exception, CancellationToken cancellationToken,
Boolean aborted) at
System.Net.WebSockets.WebSocketBase.d__45.MoveNext()
--- End of stack trace from previous location where exception was thrown --- at
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task) at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
--- End of stack trace from previous location where exception was thrown --- at
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task) at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
Here's my code:
using System;
using System.Collections.Generic;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
using RTLS_GetData_From_WebSockets.App_Code;
namespace RTLS_GetData_From_WebSockets
{
class Program
{
private static object consoleLock = new object();
private const int sendChunkSize = 256;
private const int receiveChunkSize = 256;
private const bool verbose = true;
private static readonly TimeSpan delay = TimeSpan.FromMilliseconds(30000);
private static WebSocket client;
const string host = "ws://localhost:8080";
static void Main(string[] args)
{
Connect(host).Wait();
}
public static async Task Connect(string uri)
{
ClientWebSocket webSocket = null;
try
{
webSocket = new ClientWebSocket();
await webSocket.ConnectAsync(new Uri(uri), CancellationToken.None);
List<Task> tasks = new List<Task>();
tasks.Add(Receive(webSocket));
tasks.Add(Send(webSocket, "9"));
tasks.Add(Send(webSocket, "10"));
tasks.Add(Send(webSocket, "11"));
await Task.WhenAll(tasks);
}
catch (Exception ex)
{
Console.WriteLine("Exception: {0}", ex);
}
finally
{
if (webSocket != null)
webSocket.Dispose();
Console.WriteLine();
lock (consoleLock)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("WebSocket closed.");
Console.ResetColor();
}
}
}
static UTF8Encoding encoder = new UTF8Encoding();
private static async Task Send(ClientWebSocket webSocket, string ZoneID)
{
byte[] buffer = encoder.GetBytes("{\"method\":\"subscribe\", \"resource\":\"/zones/" + ZoneID + "\"}");
await webSocket.SendAsync(new ArraySegment<byte>(buffer), WebSocketMessageType.Text, true, CancellationToken.None);
while (webSocket.State == WebSocketState.Open)
{
LogStatus(false, buffer, buffer.Length);
await Task.Delay(delay);
}
}
private static async Task Receive(ClientWebSocket webSocket)
{
byte[] buffer = new byte[receiveChunkSize];
while (webSocket.State == WebSocketState.Open)
{
var result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
if (result.MessageType == WebSocketMessageType.Close)
{
await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
}
else
{
LogStatus(true, buffer, result.Count);
}
}
}
private static void LogStatus(bool receiving, byte[] buffer, int length)
{
lock (consoleLock)
{
Console.ForegroundColor = receiving ? ConsoleColor.Green : ConsoleColor.Gray;
if (verbose)
{
string tmp = encoder.GetString(buffer);
var data = JsonConvert.DeserializeObject<Zones>(tmp);
Console.WriteLine(data.body.status);
Console.WriteLine();
}
Console.ResetColor();
}
}
}
}
[DataContract]
public class Zones
{
[DataMember(Name = "body")]
public ZoneBody body { get; set; }
}
public class ZoneBody
{
[DataMember(Name = "feed_id")]
public string feed_id { get; set; }
[DataMember(Name = "zone_id")]
public string zone_id { get; set; }
[DataMember(Name = "status")]
public string status { get; set; }
[DataMember(Name = "at")]
public string at { get; set; }
}
This is from MSDN, here is the link.
This operation will not block. The returned Task object will complete
after the send request on the ClientWebSocket instance has completed.
Exactly one send and one receive is supported on each ClientWebSocket
object in parallel.
Call your Connect method one by one.

NullReferenceException when using Fluent Validation ASP.NET Core

whenever I hook up fluent validation to my asp.net core mvc app I start getting NullReferenceException, I've followed the integration guide for asp.net core on github but I can't figure it out where is failing. bellow is my model class an validator and service configuration
public void ConfigureServices(IServiceCollection services)
{
var appSettings = Configuration.GetSection("AppSettings");
services.Configure<AppSettings>(appSettings);
#region FluentValidation
services.AddTransient<IValidator<ContactFormModel>, ContactFormValidator>();
services.AddTransient<IValidator<BookingSearchViewModel>, BookingSearchModelValidator>();
services.AddTransient<IValidator<BookingCarSelectionViewModel>, BookingCarSelectionValidator>();
services.AddTransient<IValidator<BookingClientDataModel>, BookingClientDataValidator>();
#endregion
services.AddMvc().AddFluentValidation();
services.AddAutoMapper(typeof(Startup));
}
my model class and validator
public class BookingSearchViewModel
{
[Display(Name ="Fecha de Recogida")]
public DateTime? PickupDate { get; set; }
[Display(Name = "Fecha de Entrega")]
public DateTime? DropoffDate { get; set; }
[Display(Name = "Transmisión")]
public CarTransmissionEnum Transmission { get; set; }
public List<SelectListItem> transmissionOptions { get; set; }
public BookingSearchViewModel()
{
var list = new List<string>
{
"Manual",
"Automatico"
};
this.transmissionOptions = new List<SelectListItem> {
new SelectListItem
{
Text="Manual"
},
new SelectListItem
{
Text="Automatico"
}
};
}
}
public class BookingSearchModelValidator : AbstractValidator<BookingSearchViewModel>
{
public BookingSearchModelValidator()
{
RuleFor(x => x.PickupDate).NotNull().GreaterThan(DateTime.Now).Must(FiveDaysFromToday);
RuleFor(x => x.DropoffDate).NotNull().GreaterThan(x => x.PickupDate).Must((form, countyId) => BeAValidRange(form.PickupDate, form.DropoffDate));
RuleFor(x => x.Transmission).IsInEnum();
}
private bool FiveDaysFromToday(DateTime? pickupDate)
{
if (pickupDate.HasValue)
{
var today = DateTimeOffset.UtcNow.Date.ToCST().DateTime;
var days = pickupDate.Value.Date.ToCST().Subtract(today).Days;
return days > 3;
}
return false;
}
private bool BeAValidRange(DateTimeOffset? pickupDate, DateTimeOffset? dropoffDate)
{
if (pickupDate.HasValue && dropoffDate.HasValue)
{
var days = dropoffDate.Value.Subtract(pickupDate.Value).Days;
if (days > 2 && days < 29)
return true;
}
return false;
}
}
this is the stack trace
NullReferenceException: Object reference not set to an instance of an object.
FluentValidation.AspNetCore.FluentValidationClientModelValidatorProvider.CreateValidators(ClientValidatorProviderContext context)
Microsoft.AspNetCore.Mvc.ModelBinding.Validation.CompositeClientModelValidatorProvider.CreateValidators(ClientValidatorProviderContext context)
Microsoft.AspNetCore.Mvc.Internal.ClientValidatorCache.GetValidators(ModelMetadata metadata, IClientModelValidatorProvider validatorProvider)
Microsoft.AspNetCore.Mvc.ViewFeatures.DefaultValidationHtmlAttributeProvider.AddValidationAttributes(ViewContext viewContext, ModelExplorer modelExplorer, IDictionary<string, string> attributes)
Microsoft.AspNetCore.Mvc.ViewFeatures.ValidationHtmlAttributeProvider.AddAndTrackValidationAttributes(ViewContext viewContext, ModelExplorer modelExplorer, string expression, IDictionary<string, string> attributes)
Microsoft.AspNetCore.Mvc.ViewFeatures.DefaultHtmlGenerator.AddValidationAttributes(ViewContext viewContext, TagBuilder tagBuilder, ModelExplorer modelExplorer, string expression)
Microsoft.AspNetCore.Mvc.ViewFeatures.DefaultHtmlGenerator.GenerateInput(ViewContext viewContext, InputType inputType, ModelExplorer modelExplorer, string expression, object value, bool useViewData, bool isChecked, bool setId, bool isExplicitValue, string format, IDictionary<string, object> htmlAttributes)
Microsoft.AspNetCore.Mvc.ViewFeatures.DefaultHtmlGenerator.GenerateTextBox(ViewContext viewContext, ModelExplorer modelExplorer, string expression, object value, string format, object htmlAttributes)
Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper.GenerateTextBox(ModelExplorer modelExplorer, string inputTypeHint, string inputType)
Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper.Process(TagHelperContext context, TagHelperOutput output)
Microsoft.AspNetCore.Razor.TagHelpers.TagHelper.ProcessAsync(TagHelperContext context, TagHelperOutput output)
Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner+<RunAsync>d__0.MoveNext()
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.TaskAwaiter.GetResult()
AspNetCore._Views_Home_Index_cshtml+<<ExecuteAsync>b__39_7>d.MoveNext() in Index.cshtml
+
<input asp-for="PickupDate" class="form-control" placeholder="mm/dd/yyyy" required type="text" />
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext+<GetChildContentAsync>d__31.MoveNext()
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper+<ProcessAsync>d__7.MoveNext()
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner+<RunAsync>d__0.MoveNext()
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.TaskAwaiter.GetResult()
AspNetCore._Views_Home_Index_cshtml+<ExecuteAsync>d__39.MoveNext() in Index.cshtml
+
var pixelImage = appSettings.Value.PixelImage;
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Mvc.Razor.RazorView+<RenderPageCoreAsync>d__16.MoveNext()
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Mvc.Razor.RazorView+<RenderPageAsync>d__15.MoveNext()
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Mvc.Razor.RazorView+<RenderAsync>d__14.MoveNext()
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor+<ExecuteAsync>d__22.MoveNext()
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor+<ExecuteAsync>d__21.MoveNext()
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Mvc.ViewResult+<ExecuteResultAsync>d__26.MoveNext()
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker+<InvokeResultAsync>d__19.MoveNext()
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker+<InvokeNextResultFilterAsync>d__24.MoveNext()
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResultExecutedContext context)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker+<InvokeNextResourceFilter>d__22.MoveNext()
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker+<InvokeFilterPipelineAsync>d__17.MoveNext()
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker+<InvokeAsync>d__15.MoveNext()
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Builder.RouterMiddleware+<Invoke>d__4.MoveNext()
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware+<Invoke>d__7.MoveNext()
this is how I'm executing the view
public IActionResult Index()
{
var model = new BookingSearchViewModel();
return View(model);
}
I've tried removing the nullable properties in the model, initializing them, removing the validation rules but I still get the same error , I'm using FluentValidation.AspNetCore v7.2.0.
How can I fix this null exception?
**Edit:
is not a duplicate, is related to Fluent Validation and my guess the exception is happening when Injecting Fluent validation into asp.net core, none of my models are null, removing the AddFluentValidation() from the services removes the error but then I can't use fluent validation no more**
Thanks
Not sure if you need client side validation on for your particular application, but I managed to sort this by disabling client side validation (after reading the fluentvalidation issues log here)
The code I use in my startup is:-
services.AddMvc().AddFluentValidation(fv =>
{
fv.ConfigureClientsideValidation(enabled: false);
});

MIssing method in System.Web.Http.ApiController.get_Request()

I have a controller.
public sealed class AccountsController : BaseApiController
{
private readonly IDatabaseAdapter _databaseAdapter;
public AccountsController(IDatabaseAdapter databaseAdapter)
{
_databaseAdapter = databaseAdapter;
}
[AllowAnonymous]
[Route("create")]
public async Task<IHttpActionResult> CreateUser(CreateUserBindingModel createUserModel)
{
if (!ModelState.IsValid)
return BadRequest(ModelState);
if (! await _databaseAdapter.DoesAgentExist(createUserModel.UserName))
return BadRequest();
if (await _databaseAdapter.DoesAgentHaveAccount(createUserModel.UserName))
return BadRequest();
// Create account.
var password = PasswordHelper.GeneratePassword(32);
createUserModel.Password = password;
createUserModel.ConfirmPassword = password;
var user = new ApplicationUser
{
UserName = createUserModel.UserName,
};
var addUserResult = await AppUserManager.CreateAsync(user, createUserModel.Password);
if (!addUserResult.Succeeded)
return GetErrorResult(addUserResult);
var locationHeader = new Uri(Url.Link("GetUserById", new { id = user.Id }));
return Created(locationHeader, ModelFactory.Create(user));
}
}
When I send the following fiddler to the create method.
http://localhost:59430/api/accounts/create User-Agent: Fiddler
Content-Type: application/json Accept: application/json Host:
localhost:59430 Content-Length: 106
{ "UserName":"a.xxxxx", "Password":"xxxxxx",
"ConfirmPassword":"xxxxxx", }
It gets down to the following line:
var addUserResult = await AppUserManager.CreateAsync(user, createUserModel.Password);
Then the following exception occurs
{ "message": "An error has occurred.", "exceptionMessage": "Method
not found: 'System.Net.Http.HttpRequestMessage
System.Web.Http.ApiController.get_Request()'.", "exceptionType":
"System.MissingMethodException", "stackTrace": " at
WebAuth.Controllers.BaseApiController.get_AppUserManager()\r\n at
WebAuth.Controllers.AccountsController.d__3.MoveNext() in
C:\Users\stuarts\Documents\Visual Studio
2017\Projects\WebAuth\WebAuth\Controllers\AccountsController.cs:line
76\r\n--- End of stack trace from previous location where exception
was thrown ---\r\n at
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task)\r\n at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task)\r\n at
System.Threading.Tasks.TaskHelpersExtensions.d__3`1.MoveNext()\r\n---
End of stack trace from previous location where exception was thrown
---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task)\r\n at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task)\r\n at
System.Web.Http.Controllers.ApiControllerActionInvoker.d__0.MoveNext()\r\n---
End of stack trace from previous location where exception was thrown
---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task)\r\n at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task)\r\n at
System.Web.Http.Controllers.ActionFilterResult.d__2.MoveNext()\r\n---
End of stack trace from previous location where exception was thrown
---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task)\r\n at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task)\r\n at
System.Web.Http.Dispatcher.HttpControllerDispatcher.d__1.MoveNext()"
}
Anyone know what is going on? I have no idea why it can't find that method.
My bin folders contains
System.Web.Http.dll
System.Web.Http.Owin.dll
System.Net.Http.dll
ApplicationUserManager
public sealed class ApplicationUserManager : UserManager<ApplicationUser>
{
public ApplicationUserManager(IUserStore<ApplicationUser> store) : base(store)
{
}
public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options,
IOwinContext context)
{
var appDbContext = context.Get<ApplicationDbContext>();
var appUserManager = new ApplicationUserManager(new UserStore<ApplicationUser>(appDbContext));
appUserManager.UserValidator = new UserValidator<ApplicationUser>(appUserManager)
{
AllowOnlyAlphanumericUserNames = true,
RequireUniqueEmail = false,
};
appUserManager.PasswordValidator = new PasswordValidator
{
RequiredLength = 12,
RequireNonLetterOrDigit = true,
RequireUppercase = true,
RequireLowercase = true,
RequireDigit = true
};
appUserManager.MaxFailedAccessAttemptsBeforeLockout = 3;
appUserManager.DefaultAccountLockoutTimeSpan = TimeSpan.FromHours(1);
return appUserManager;
}
}
BaseApiController
public class BaseApiController : ApiController
{
private ModelFactory _modelFactory;
private readonly ApplicationUserManager _applicationUserManager = null;
protected ApplicationUserManager AppUserManager => _applicationUserManager ?? Request.GetOwinContext().GetUserManager<ApplicationUserManager>();
protected ModelFactory ModelFactory => _modelFactory ?? (_modelFactory = new ModelFactory(Request, AppUserManager));
protected IHttpActionResult GetErrorResult(IdentityResult result)
{
if (result == null)
return InternalServerError();
if (result.Succeeded) return null;
if (result.Errors != null)
foreach (var error in result.Errors)
ModelState.AddModelError(string.Empty, error);
if (ModelState.IsValid)
return BadRequest();
return BadRequest(ModelState);
}
private readonly ApplicationRoleManager _appRoleManager = null;
protected ApplicationRoleManager AppRoleManager => _appRoleManager ?? Request.GetOwinContext().GetUserManager<ApplicationRoleManager>();
}
I found a solution to this.
When I was building there was build warnings going to the output window but not showing in the main error / warning window.
They were to do with assembly conflicts and said recommend putting the assembly redirect in the web.Config.
Once I had went through them all (around 80) it now works.
e.g.
<dependentAssembly>
<assemblyIdentity name="System.Net.Http" culture="neutral" publicKeyToken="b03f5f7f11d50a3a" />
<bindingRedirect oldVersion="0.0.0.0-4.2.0.0" newVersion="4.2.0.0" />
</dependentAssembly>

Property null in web api controller when using Entity Framework 5 and Oracle

i have a problem in a new web api controller when i try to use EF5 with Oracle.
My controller:
public class DeviceV1Controller : ApiController
{
private readonly IDevice _repository;
public DeviceV1Controller()
{
IDevice _repository = new EFDeviceRepository();
}
[Route("api/Device/{hashImei}/app/{nome}")]
public HttpResponseMessage Post(string hashImei, string nome, [FromBody] DeviceInfo deviceInfo)
{
_repository.Add(deviceInfo);
return Request.CreateResponse(HttpStatusCode.OK);
}
}
_repository is correctly bound in the constructor, but entering the Post api this variable become null and i get this error:
{
message: "An error has occurred."
exceptionMessage: "object reference not set to an instance of an object."
exceptionType: "System.NullReferenceException"
stackTrace: " in MpssApiRest.Controllers.DeviceV1Controller.Post(String hashImei, String nome, DeviceInfo deviceInfo) in c:\SVILUPPO\MpssApiRest\MpssApiRest\MpssApiRest\Controllers\DeviceV1Controller.cs:riga 28 in lambda_method(Closure , Object , Object[] ) in System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass10.<GetExecutor>b__9(Object instance, Object[] methodParameters) in System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments) in System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken) --- Fine traccia dello stack da posizione precedente dove è stata generata l'eccezione --- in System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) in System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) in System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__0.MoveNext() --- Fine traccia dello stack da posizione precedente dove è stata generata l'eccezione --- in System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) in System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) in System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext() --- Fine traccia dello stack da posizione precedente dove è stata generata l'eccezione --- in System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) in System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) in System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__0.MoveNext()"
}
EFDeviceRepository concrete class is:
public class EFDeviceRepository : IDevice
{
private readonly EntityDevice ctx;
public EFDeviceRepository()
{
ctx = new EntityDevice();
}
public void Add(Models.V1.DeviceInfo deviceInfo)
{
EntityDevice ctx = new EntityDevice();
MPSS_APP_DEVICE device = new MPSS_APP_DEVICE();
device.HASHIMEI = deviceInfo.HashImei;
ctx.MPSS_APP_DEVICE.Add(device);
ctx.SaveChanges();
}
}
Thanks
EDIT: Sample Web Request (retrieved from the comments)
Ip Address: 192.168.1.129
Url: /myproject/api/device/123456/app/appname
JSON:
{
"applicazione" : "Gestione Interventi",
"hashImei" : "123123121323123121",
"modello" : "Nexus 5",
"pushNotificatioToken" : "oifjwfijowfjfoiwjrgfoirwj42rohfoifrj",
"sistemaOperativo" : "ANDROID", "versione" : "LOLLIPOP_MR1"
}
The reason why _repository is null in your Action is because you are not initializing it in your constructor. Instead you have declared and initialized a local variable of the same name in your constructor!
public class DeviceV1Controller : ApiController
{
private readonly IDevice _repository;
public DeviceV1Controller()
{
_repository = new EFDeviceRepository();
}
// ...
}

Categories

Resources