DbContext SaveChangesAsync Exception - asp.net-mvc

I want to make new ride, for it I have this code:
using (var db = new CarManagerDbEntities())
{
Guid? carId = GetCarId(carLicenceId);
if (carId == null)
{
return null;
}
Guid rideId = Guid.NewGuid();
Ride newRide = new Ride() { DriverID = driverId, CarID = carId.Value, StartDrive= startTime, Id = rideId};
db.Ride.Add(newRide);
await db.SaveChangesAsync();
return carId;
}
but in the line:
await db.SaveChangesAsync();
I get this exception:
System.ServiceModel.FaultException`1 was unhandled
HResult=-2146233087
Message=An error occurred while updating the entries. See the inner exception for details.
Source=mscorlib
StackTrace:
Server stack trace:
at System.ServiceModel.Channels.ServiceChannel.ThrowIfFaultUnderstood(Message reply, MessageFault fault, String action, MessageVersion version, FaultConverter faultConverter)
at System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime operation, ProxyRpc& rpc)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at CarManager.TestingCLI.CarManagerServiceReference.ICarManagerApi.StartNewRide(Guid driverId, DateTime startTime, String carLicenceId)
at CarManager.TestingCLI.CarManagerServiceReference.CarManagerApiClient.StartNewRide(Guid driverId, DateTime startTime, String carLicenceId) in c:\Projetcs\CarManager.TestingCLI\Service References\CarManagerServiceReference\Reference.cs:line 990
at CarManager.TestingCLI.Program.Main(String[] args) in c:\Projetcs\CarManager.TestingCLI\Program.cs:line 17
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
The inner exception is null.
What I'm not doing right?

Related

Why is this crashing on Delete, and why are null values passed into it?

I'm having some difficulty with crashing code in a Delete method (MVC). Here are two methods in my ProductItem controller class. The "Delete" works fine, but I'm getting an error message and when I step through, I notice that the DeleteConfirmed below it is getting a null value for prodID (itemID passes in fine). I have a tough time troubleshooting this because I don't know how the DeleteConfirmed method is being "called" or how the values are getting passed in (or supposed to be passed in) so I don't know what to trace or step through.
EDIT: I removed the nullable from the two arguments for itemID and productID, now it doesn't even get to DeleteConfirmed, I get this:
[ArgumentException: The parameters dictionary contains a null entry for parameter 'prodID' of non-nullable type 'System.Int32' for method 'System.Threading.Tasks.Task`1[System.Web.Mvc.ActionResult] DeleteConfirmed(Int32, Int32)' in 'Memberships.Areas.Admin.Controllers.ProductItemController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
Parameter name: parameters]
System.Web.Mvc.ActionDescriptor.ExtractParameterFromDictionary(ParameterInfo parameterInfo, IDictionary`2 parameters, MethodInfo methodInfo) +527
System.Web.Mvc.Async.<>c__DisplayClass20_0.<BeginExecute>b__0(ParameterInfo parameterInfo) +19
System.Linq.WhereSelectArrayIterator`2.MoveNext() +58
System.Linq.Buffer`1..ctor(IEnumerable`1 source) +196
System.Linq.Enumerable.ToArray(IEnumerable`1 source) +79
System.Web.Mvc.Async.TaskAsyncActionDescriptor.BeginExecute(ControllerContext controllerContext, IDictionary`2 parameters, AsyncCallback callback, Object state) +152
System.Web.Mvc.Async.<>c__DisplayClass8_0.<BeginInvokeAsynchronousActionMethod>b__0(AsyncCallback asyncCallback, Object asyncState) +28
System.Web.Mvc.Async.WrappedAsyncResult`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +14
System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128
System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAsynchronousActionMethod(ControllerContext controllerContext, AsyncActionDescriptor actionDescriptor, IDictionary`2 parameters, AsyncCallback callback, Object state) +179
System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters, AsyncCallback callback, Object state) +45
System.Web.Mvc.Async.AsyncInvocationWithFilters.InvokeActionMethodFilterAsynchronouslyRecursive(Int32 filterIndex) +87
System.Web.Mvc.Async.AsyncInvocationWithFilters.InvokeActionMethodFilterAsynchronouslyRecursive(Int32 filterIndex) +629
System.Web.Mvc.Async.<>c__DisplayClass7_0.<BeginInvokeActionMethodWithFilters>b__0(AsyncCallback asyncCallback, Object asyncState) +58
System.Web.Mvc.Async.WrappedAsyncResult`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +14
System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128
System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters, AsyncCallback callback, Object state) +197
System.Web.Mvc.Async.<>c__DisplayClass3_1.<BeginInvokeAction>b__0(AsyncCallback asyncCallback, Object asyncState) +640
System.Web.Mvc.Async.WrappedAsyncResult`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +14
System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128
System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext, String actionName, AsyncCallback callback, Object state) +346
System.Web.Mvc.<>c.<BeginExecuteCore>b__152_0(AsyncCallback asyncCallback, Object asyncState, ExecuteCoreState innerState) +27
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +30
System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128
System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state) +494
System.Web.Mvc.<>c.<BeginExecute>b__151_1(AsyncCallback asyncCallback, Object callbackState, Controller controller) +16
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +20
System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128
System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +403
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +16
System.Web.Mvc.<>c.<BeginProcessRequest>b__20_0(AsyncCallback asyncCallback, Object asyncState, ProcessRequestState innerState) +54
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +30
System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +427
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +48
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +105
System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +50
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +163
// GET: Admin/ProductItem/Delete/5
public async Task<ActionResult> Delete(int? itemID, int? productID)
{
if (itemID == null || productID == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Product_Item product_Item = await GetProductItem(itemID, productID);
if (product_Item == null)
{
return HttpNotFound();
}
return View(await product_Item.Convert(db));
}
// POST: Admin/ProductItem/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> DeleteConfirmed(int itemID, int prodID)
{
Product_Item product_Item = await GetProductItem(itemID, prodID);
db.Products_Items.Remove(product_Item);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
As requested: The View Model
using Memberships.Entities;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace Memberships.Areas.Admin.Models
{
public class ProductItemModel
{
[DisplayName("Product ID")]
public int ProductID { get; set; }
[DisplayName("Item ID")]
public int ItemID { get; set; }
[DisplayName("Product")]
public string ProductTitle { get; set; }
[DisplayName("Item")]
public string ItemTitle { get; set; }
public ICollection<Product> Products { get; set; }
public ICollection<Item> Items { get; set; }
}
}
public static async Task<ProductItemModel> Convert
(this Product_Item productItem, ApplicationDbContext db, bool addListData=true)
//Only fill collections if the parameter passed in is true
{
var model = new ProductItemModel
{
ItemID = productItem.ItemID,
ProductID = productItem.ProductID,
Items = addListData ? await db.Items.ToListAsync() : null,
Products = addListData ? await db.Products.ToListAsync() : null,
ItemTitle = (await db.Items.FirstOrDefaultAsync(i => i.ID.Equals(productItem.ItemID))).Title,
ProductTitle = (await db.Products.FirstOrDefaultAsync(p => p.ID.Equals(productItem.ProductID))).Title
};
return model;
}
private async Task<Product_Item> GetProductItem(int? item, int? prod)
{
try
{
int itemID = 0, prodID = 0;
int.TryParse(item.ToString(), out itemID);
int.TryParse(prod.ToString(), out prodID);
var productItem = await db.Products_Items.FirstOrDefaultAsync
(
pi => pi.ProductID.Equals(prodID) && pi.ItemID.Equals(itemID)
);
return productItem;
}
catch {return null;}
}
I figured it out, oddly enough when I had to copy the code and paste it for a new function. The problem was in the delete button itself. The model used to build the parameter string for the Edit Details and Delete buttons (code pasted below) uses "ProductID" for a parameter name, yet the controller's delete method used the argument ProdID instead of ProductID so it was coming in null!!
public string ActionParameters //Build a string containing any id paramaters which are passed in.
{
get
{
var param = new StringBuilder("?");
if(ID != null && ID>0)
{ //If the ID is not null then "id=<ID>" will be appended to the parameter string.
param.Append(String.Format("{0}={1}&","id",ID));
}
if ((ItemID ?? 0) > 0)
{ //If the ID is not null then "id=<ID>" will be appended to the parameter string.
param.Append(String.Format("{0}={1}&", "ItemID", ItemID));
}
if ((ProductID ?? 0) > 0)
{ //If the ID is not null then "id=<ID>" will be appended to the parameter string.
**param.Append(String.Format("{0}={1}&", "ProductID", ProductID));**
}
if ((SubscriptionID ?? 0) > 0)
{ //If the ID is not null then "id=<ID>" will be appended to the parameter string.
param.Append(String.Format("{0}={1}&", "Subscription", SubscriptionID));
}
return param.ToString().Substring(0,param.Length-1); //Remove last "&"
}
I found this when I had to copy and paste the code for a similar function and noticed that the arguments didn't match.
Thanks for everyone who contributed!

Object reference not set to an instance of an object when using Authorization with Roles

I am trying to use Aspnet with Roles. With the NRE, still I cannot figure out what to instantiate.
This is in the controller
[Authorize(Roles = "Admin")]
public ActionResult ForAdmin()
{
return View();
}
This is how I authorize
public Programmer GetLoginCredentials(Login credential)
{
Programmer programmer = null;
HttpContext.Current.Session["ProgrammerName"] = null;
HttpContext.Current.Session["Roles"] = null;
using (
var cmd = new SqlCommand("Sp_GetLoginCredentials", _dbConnection)
{
CommandType = CommandType.StoredProcedure
})
{
try
{
cmd.Parameters.AddWithValue("#Username", credential.Username);
cmd.Parameters.AddWithValue("#Password", credential.Password);
var da = new SqlDataAdapter(cmd);
var ds = new DataSet();
da.Fill(ds);
if (ds.Tables[0].Rows.Count <= 0) return null;
foreach (DataRow row in ds.Tables[0].Rows)
{
programmer = new Programmer()
{
ProgrammerId = Convert.ToInt32(row["ProgrammerId"]),
ProgrammerName = row["ProgrammerName"].ToString(),
Username = row["Username"].ToString(),
Password = row["Password"].ToString()
};
HttpContext.Current.Session["ProgrammerName"] = programmer.ProgrammerName;
}
if (programmer != null)
{
GetRoles(programmer);
}
return programmer;
}
catch
{
return null;
}
}
}
This is how I fill the session with roles
public List<Role> GetRoles(Programmer credential)
{
var roleList = new List<Role>();
using (var cmd = new SqlCommand("Sp_GetRoles", _dbConnection) {CommandType = CommandType.StoredProcedure})
{
cmd.Parameters.AddWithValue("#Username", credential.Username);
cmd.Parameters.AddWithValue("#Password", credential.Password);
var da = new SqlDataAdapter(cmd);
var ds = new DataSet();
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
roleList.AddRange(from DataRow row in ds.Tables[0].Rows
select new Role()
{
RoleName = row["RoleName"].ToString()
});
}
HttpContext.Current.Session["Roles"] = roleList;
}
return roleList;
}
This is my role provider
public class SiteRole : RoleProvider
{
public override string[] GetRolesForUser(string username)
{
var data = HttpContext.Current.Session["Roles"];
return data as string[];
}
}
In my Session["Roles"] I get it like this
So that means I am able to get the "Admin" role but in my browser, I get this error:
[NullReferenceException: Object reference not set to an instance of an object.]
System.Web.Security.RolePrincipal.IsInRole(String role) +9803940
System.Linq.Enumerable.Any(IEnumerable`1 source, Func`2 predicate) +146
System.Web.Mvc.AuthorizeAttribute.AuthorizeCore(HttpContextBase httpContext) +333
System.Web.Mvc.AuthorizeAttribute.OnAuthorization(AuthorizationContext filterContext) +379
System.Web.Mvc.ControllerActionInvoker.InvokeAuthorizationFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor) +143
System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__19(AsyncCallback asyncCallback, Object asyncState) +1680
System.Web.Mvc.Async.WrappedAsyncResult`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +59
System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +151
System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate`1 endDelegate, Object tag, Int32 timeout) +94
System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext, String actionName, AsyncCallback callback, Object state) +559
System.Web.Mvc.Controller.<BeginExecuteCore>b__1c(AsyncCallback asyncCallback, Object asyncState, ExecuteCoreState innerState) +82
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +73
System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +151
System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object callbackState, BeginInvokeDelegate`1 beginDelegate, EndInvokeVoidDelegate`1 endDelegate, TState invokeState, Object tag, Int32 timeout, SynchronizationContext callbackSyncContext) +105
System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state) +588
System.Web.Mvc.Controller.<BeginExecute>b__14(AsyncCallback asyncCallback, Object callbackState, Controller controller) +47
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +65
System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +151
System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object callbackState, BeginInvokeDelegate`1 beginDelegate, EndInvokeVoidDelegate`1 endDelegate, TState invokeState, Object tag, Int32 timeout, SynchronizationContext callbackSyncContext) +139
System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +484
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +50
System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__4(AsyncCallback asyncCallback, Object asyncState, ProcessRequestState innerState) +98
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +73
System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +151
System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object callbackState, BeginInvokeDelegate`1 beginDelegate, EndInvokeVoidDelegate`1 endDelegate, TState invokeState, Object tag, Int32 timeout, SynchronizationContext callbackSyncContext) +106
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +446
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +88
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +50
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +103
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
Can you please show me where I am getting it wrong? Thank you.
You cannot cast HttpContext.Current.Session["Roles"] to string[] because it's of type List<Role>
Try this instead:
public override string[] GetRolesForUser(string username)
{
var data = HttpContext.Current.Session["Roles"] as IEnumerable<Role>;
return data.Select(d => d.RoleName).ToArray();
}

Exception only in Internet Explorer : "The required anti-forgery form field "__RequestVerificationToken" is not present"

I know there is lots of similar questions about this, but this is different:
This exception happens ONLY in IE.
Also this is in login page. There is #Html.AntiForgeryToken() on the form and with or without using this:
var addAntiForgeryToken = function (data, form) {
data.__RequestVerificationToken = $("#" + form + " input[type=hidden] [name='__RequestVerificationToken']").val();
return data;
};
var formdata = addAntiForgeryToken($(this), 'login-form').serialize(),
the __RequestVerificationToken field is always present in the formdata(in debug mode of IE); but always ajax login function returns this exception. Why?
The required anti-forgery form field "__RequestVerificationToken" is not present.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Web.Mvc.HttpAntiForgeryException: The required anti-forgery form field "__RequestVerificationToken" is not present.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[HttpAntiForgeryException (0x80004005): The required anti-forgery form field "__RequestVerificationToken" is not present.]
System.Web.Helpers.AntiXsrf.TokenValidator.ValidateTokens(HttpContextBase httpContext, IIdentity identity, AntiForgeryToken sessionToken, AntiForgeryToken fieldToken) +485
System.Web.Helpers.AntiXsrf.AntiForgeryWorker.Validate(HttpContextBase httpContext) +71
System.Web.Helpers.AntiForgery.Validate() +92
System.Web.Mvc.ValidateAntiForgeryTokenAttribute.OnAuthorization(AuthorizationContext filterContext) +18
System.Web.Mvc.ControllerActionInvoker.InvokeAuthorizationFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor) +97
System.Web.Mvc.Async.<>c__DisplayClass21.<begininvokeaction>
b__19(AsyncCallback asyncCallback, Object asyncState) +743
System.Web.Mvc.Async.WrappedAsyncResult`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +14
System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128
System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext, String actionName, AsyncCallback callback, Object state) +343
System.Web.Mvc.Controller.<beginexecutecore>
b__1c(AsyncCallback asyncCallback, Object asyncState, ExecuteCoreState innerState) +25
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +30
System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128
System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state) +465
System.Web.Mvc.Controller.<beginexecute>
b__14(AsyncCallback asyncCallback, Object callbackState, Controller controller) +18
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +20
System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128
System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +374
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +16
System.Web.Mvc.MvcHandler.<beginprocessrequest>
b__4(AsyncCallback asyncCallback, Object asyncState, ProcessRequestState innerState) +52
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +30
System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +384
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +48
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +301
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
Update:
My Ajax script code to login:
$(function () {
configValidations();
$('#login-form').submit(function (e) {
e.preventDefault();
$("#result").html("");
if ($(this).valid()) {
var formdata = $('#login-form').serialize();
wait();
$.ajax({
url: this.action,
type: this.method,
cache: false,
data: formdata,
dataType: "json",
success: function (result) {
$('#result').html(ajaxSuccessMessage(""));
}
}).done(function (response) {
unwait();
if (response.Content == null) {
$("#result").html(ajaxErrorMessage(response.Errors[0]));
}
else {
window.location = response.Content
}
}).fail(function (error) {
$('#result').html(ajaxValidationBootstrap(error));
}).always(function () {
unwait();
});
}
});
});
The serialized data is present like this:(But it says it is not present)
__RequestVerificationToken=BsLh3rc3zlgSna8CDaAN-sK7MsDL4ch0mjk8aW3eKtusSC1MYR4lAEo7HNJz3erAdi2Z3NvrXndFUoFw9FGL5SKTYp_HvFJI-TUg_neb9GQ1&ReturnUrl=&email=demo%40email.com&UserName=demouser&Password=demopasse

Object not set to instance when calling RedirectToAction

IIS Throws:
Object reference not set to an instance of an object.
when it is supposed to redirect a authenticated user to /Home/Index
I have investigated the reason it might be happening and can´t find the reason
The line is that:
return RedirectToAction("Index", "Home");
stacktrace: (That is the only information I get)
[NullReferenceException: Object reference not set to an instance of an object.]
System.Web.Mvc.AuthorizeAttribute.AuthorizeCore(HttpContextBase httpContext) +30
System.Web.Mvc.AuthorizeAttribute.OnAuthorization(AuthorizationContext filterContext) +160
System.Web.Mvc.ControllerActionInvoker.InvokeAuthorizationFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor) +97
System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__1e(AsyncCallback asyncCallback, Object asyncState) +445
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +129
System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext, String actionName, AsyncCallback callback, Object state) +287
System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__17(AsyncCallback asyncCallback, Object asyncState) +30
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +129
System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state) +338
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +129
System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +282
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +15
System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__2(AsyncCallback asyncCallback, Object asyncState) +71
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +129
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +236
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +48
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +301
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
Edit 1:
The application is working locally in my computer. I am coping all the folder and sending to the server. Then, I try to access locally in the server and I get this. IIS on the server has the same configuration for Application Pool and I believe it is configured right, at least for a local use as I am doing. I am trying to get it to work locally in the server and then I´ll configure for remote use.
Edit 2:
This is /Home/Index:
namespace gedaiapp.Controllers
{
[Authorize]
public class HomeController : Controller
{
public ActionResult Index()
{
return PartialView();
}
}
}
and the /Index/Login (Class has authorize attribute, only this specific method has [AllowAnonymous]) so users not yet authenticated are allowed to login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginModel model, FormCollection form)
{
try
{
//Verifica se logon será feito utilizando certificado digital ou não
string isDigitalCertified = form["hasDigital"];
if (!string.IsNullOrEmpty(isDigitalCertified))
{
string[] isDCArr = isDigitalCertified.Split(',');
if (!string.IsNullOrEmpty(isDCArr[0]))
{
string isDC = isDCArr[0];
//Se login for utilizando certificado digital
if (isDC == "true")
{
//Resgata subject do certificado digital
string certDadosStr = "";
do
{
certDadosStr = Request.ClientCertificate.Subject;
} while (certDadosStr == "");
//Resgata cpf ou cnpj do certificado digital
string[] certDadosArr = certDadosStr.Split(',');
int Count = certDadosArr.Count();
//Razão social é sempre o último elemento no padrão ICP-Brasil
string razaoSocial = certDadosArr[Count - 1];
string[] razaoSocialArr = razaoSocial.Split(':');
Count = razaoSocialArr.Count();
string key = razaoSocialArr[Count - 1];
//Resgata Guid do usuário
MembershipUser user = Membership.GetUser(model.UserName);
Guid userID = (Guid)user.ProviderUserKey;
//Verifica se (cpf ou cnpj) do usuário efetuando o login é o mesmo do cadastrado no sistema
using (gedaiappEntities context = new gedaiappEntities())
{
var keyNumberObj = from a in context.sistema_UsersCertified
where a.userID == userID
select a.keyNumber;
string keyNumber = keyNumberObj.First();
//Se autenticidade for positiva (redireciona)
if (keyNumber == key)
{
FormsAuthentication.SetAuthCookie(model.UserName, false);
return RedirectToAction("Index", "Home");
}
else
{
return RedirectToAction("Login", "Account");
}
}
}//Caso login seja sem certificado digital
else
{
MembershipProvider mp = Membership.Provider;
if (mp.ValidateUser(model.UserName, model.Password))
{
FormsAuthentication.SetAuthCookie(model.UserName, false);
try
{
return RedirectToAction("Index", "Home");
}
catch (Exception e)
{
return Content("Erro: " + e);
}
}
return RedirectToAction("Login", "Account");
}
}
else
{
//return Content("Erro Catastrófico: Não foi possivel identificar se login é com certificado digital ou não.");
return RedirectToAction("Login", "Account");
}
}
else
{
//return Content("Erro Catastrófico: Valor do checkbox hasDigital não foi enviado.");
return RedirectToAction("Login", "Account");
}
}
catch (Exception e)
{
return Content("Erro: " + e);
}
}
Any help?
Solved the problem adding
<modules runAllManagedModulesForAllRequests="true"/>
in the web.config
P.S. It is not the right way to do as it will load all modules at every request. Although can´t find what is not loading.

ArgumentNullException when streaming files via WCF

I have a WCF streaming binary files. Below is a shortened version of the contract.
[MessageContract()]
public class DocumentTransfer
{
[MessageHeader(MustUnderstand = true)]
public string Title { get; set; }
[MessageHeader(MustUnderstand = true)]
public string FileName { get; set; }
[MessageBodyMember(Order = 1)]
public System.IO.Stream Data;
}
Everything works fine but there are scenarios when only some other values associated with the file need to be updated but not the file itself. In that case the client sets Data = null. The Data property then cannot be interpreted/serialized and throws this exception:
System.ServiceModel.Dispatcher.StreamFormatter.Serialize(XmlDictionaryWriter writer, Object[] parameters, Object returnValue)
System.ServiceModel.Dispatcher.OperationFormatter.SerializeBodyContents(XmlDictionaryWriter writer, MessageVersion version, Object[] parameters, Object returnValue, Boolean isRequest)
System.ServiceModel.Dispatcher.OperationFormatter.OperationFormatterMessage.OperationFormatterBodyWriter.OnWriteBodyContents(XmlDictionaryWriter writer)
System.ServiceModel.Channels.BodyWriter.WriteBodyContents(XmlDictionaryWriter writer)
System.ServiceModel.Channels.BodyWriterMessage.OnWriteBodyContents(XmlDictionaryWriter writer)
System.ServiceModel.Channels.Message.OnWriteMessage(XmlDictionaryWriter writer)
System.ServiceModel.Channels.Message.WriteMessage(XmlDictionaryWriter writer)
System.ServiceModel.Channels.TextMessageEncoderFactory.TextMessageEncoder.WriteMessage(Message message, Stream stream)
System.ServiceModel.Channels.HttpOutput.WriteStreamedMessage(TimeSpan timeout)
System.ServiceModel.Channels.HttpOutput.Send(TimeSpan timeout)
System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.SendRequest(Message message, TimeSpan timeout)
System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)
System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout)
System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs)
System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
...UploadDocument(DocumentTransfer request)
...UploadDocument(DocumentTransfer request) in ...
Any ideas guys?
You are getting the error in SerializeBodyContents when the body is null.
You can either create a different operation for when you do not have a file, or put a byte in the stream to avoid the exception. The first of these options is preferable, the last if you cannot change the contract.
Another option would be to return Stream.Null.

Resources