MVC 2 and ASP.NET 4 Request Validation Exception - c#

I am working on an application that I inherited from another dev shop that I recently upgraded to MVC2/.NET 4 from MVC 1/.NET 2/3.5. Everything is working fine with the exception of one page. On this page there is an iframe that loads up an instance of TinyMCE and allows for inline editing of some HTML templates. On the hosting page there is a JavaScript event wired up to the submit button that, when clicked, grabs the innerHtml value of the iframe, converts it into JSON, and places it into a hidden form field.
As the form posts I get the infamous 'A potentially dangerous Request.Form value was detected..." Now I followed Microsoft's whitepaper and added
<httpRuntime requestValidationMode="2.0" />
To my web.config and decorated my Controller with
[ValidateInput(false)]
And I am still getting this error. The relevant stack is below.
[HttpRequestValidationException (0x80004005): A potentially dangerous Request.Form value was detected from the client (HtmlContent="...orrectly? <a href=\"*|ARCHIVE|...").]
System.Web.HttpRequest.ValidateString(String value, String collectionKey, RequestValidationSource requestCollection) +8730676
System.Web.HttpRequest.ValidateNameValueCollection(NameValueCollection nvc, RequestValidationSource requestCollection) +122
System.Web.HttpRequest.get_Form() +114
System.Web.HttpRequestWrapper.get_Form() +11
System.Web.Mvc.HttpRequestExtensions.GetHttpMethodOverride(HttpRequestBase request) +235
System.Web.Mvc.AcceptVerbsAttribute.IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo) +119
System.Web.Mvc.<>c__DisplayClass11.<RunSelectionFilters>b__d(ActionMethodSelectorAttribute attr) +57
System.Linq.Enumerable.All(IEnumerable`1 source, Func`2 predicate) +145
System.Web.Mvc.ActionMethodSelector.RunSelectionFilters(ControllerContext controllerContext, List`1 methodInfos) +524
System.Web.Mvc.ActionMethodSelector.FindActionMethod(ControllerContext controllerContext, String actionName) +122
System.Web.Mvc.ReflectedControllerDescriptor.FindAction(ControllerContext controllerContext, String actionName) +182
System.Web.Mvc.ControllerActionInvoker.FindAction(ControllerContext controllerContext, ControllerDescriptor controllerDescriptor, String actionName) +47
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +283
System.Web.Mvc.Controller.ExecuteCore() +136
System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +111
System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +39
System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__4() +65
System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +44
System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +42
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +140
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +54
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +52
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +38
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8836913
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184
Interestingly is that if I hook the BeginRequest method in the Global.asax which would seem to indicate that the code is running under the 2.0 mode of request validation since, if my understanding of .NET 4s request validation is correct, I would not be able to get to this method if the code was running under 4.0 validation model since it processes everything before BeginRequest.
Now I was able to circumvent this problem by calling escape() from a JavaScript function on the the value of the hidden form field but that is, obviously, a hack. Has anyone else experienced this issue or have any idea what I can do to properly disable Request Validation for this method on my controller?
Thanks!

Check if your "pages" section in web.config looks like:
<pages validateRequest="false" ...>...</pages>
if not try to add validateRequest attribute. It works for me cause I had the same problem few months ago.
edit: lol, I didn't see that it is so old post. but I leave my answear, cause maybe it helps someone else

Related

How to Properly Get Nested Folders to Render in MVC 5 C#

I've got the traditional website with all MVC 5 working as expected, everything renders correctly and works fine.
I've added a Dashboard and this dashboard I am attempting to set to folder structure up to where it is isolated from the rest of the MVC 5 C# website; however, I'm receiving a Server Error stating that the layout engine cannot find my Partial views.
Now, when the view itself loads this is passing the test and is indeed returning the correct view, the problem is coming in when the layout engine cannot locate the nested Partial Views.
I am lost on this one due to the fact that I do not have a MVC 5 full understanding.
Now, like mentioned before everything works perfectly in regards to the out of the box folder structure but when I create a nested folder and put Partial Views the MVC 5 engine cannot locate these nested Partial Views.
The reason being nesting these Partial Views is obvious I am separating the actual traditional website from the User Dashboard views.
When I click the action link pointing to the Index file this works but when the body, The View, trys to render it cannot find the nested Partial Views.
What am I missing here? I hope that I am providing enough information that make answering this question as easy as possible.
Loading the Actual User Dashboard Index Works
#{
ViewBag.Title = "Your Dashboard";
Layout = "~/Views/Shared/UserDashboard/_Layout_Dashboard.cshtml";
}
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
Loading the actual Partials is where the Server says NO NO, you're not doing this correctly.
Here is the Exact Server Error, Please Advise Me On The Proper Way to Implement this.
Server Error in '/' Application.
The partial view '~/Views/Shared/UserDashboard/_PartialHeader_Dashboard' was not found or no view engine supports the searched locations. The following locations were searched:
~/Views/Shared/UserDashboard/_PartialHeader_Dashboard
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.InvalidOperationException: The partial view '~/Views/Shared/UserDashboard/_PartialHeader_Dashboard' was not found or no view engine supports the searched locations. The following locations were searched:
~/Views/Shared/UserDashboard/_PartialHeader_Dashboard
Source Error:
Line 26: <script src="http://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>*#
Line 27: <body>
Line 28: #Html.Partial("~/Views/Shared/UserDashboard/_PartialHeader_Dashboard")
Line 29: #Html.Partial("~/Views/Shared/UserDashboard/_PartialLeftNav_Dashboard")
Line 30: #RenderBody()
Source File: D:\Users\Erik\Documents\visual studio 2017\Projects\BuilderBits\BuilderBits\Views\Shared\UserDashboard\_Layout_Dashboard.cshtml Line: 28
Stack Trace:
[InvalidOperationException: The partial view '~/Views/Shared/UserDashboard/_PartialHeader_Dashboard' was not found or no view engine supports the searched locations. The following locations were searched:
~/Views/Shared/UserDashboard/_PartialHeader_Dashboard]
System.Web.Mvc.HtmlHelper.FindPartialView(ViewContext viewContext, String partialViewName, ViewEngineCollection viewEngineCollection) +327
System.Web.Mvc.HtmlHelper.RenderPartialInternal(String partialViewName, ViewDataDictionary viewData, Object model, TextWriter writer, ViewEngineCollection viewEngineCollection) +264
System.Web.Mvc.Html.PartialExtensions.Partial(HtmlHelper htmlHelper, String partialViewName, Object model, ViewDataDictionary viewData) +91
System.Web.Mvc.Html.PartialExtensions.Partial(HtmlHelper htmlHelper, String partialViewName) +32
ASP._Page_Views_Shared_UserDashboard__Layout_Dashboard_cshtml.Execute() in D:\Users\Erik\Documents\visual studio 2017\Projects\BuilderBits\BuilderBits\Views\Shared\UserDashboard\_Layout_Dashboard.cshtml:28
System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +197
System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +105
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +90
System.Web.WebPages.<>c__DisplayClass3.<RenderPageCore>b__2(TextWriter writer) +232
System.Web.WebPages.HelperResult.WriteTo(TextWriter writer) +10
System.Web.WebPages.WebPageBase.Write(HelperResult result) +80
System.Web.WebPages.WebPageBase.RenderSurrounding(String partialViewName, Action`1 body) +63
System.Web.WebPages.WebPageBase.PopContext() +237
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +98
System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +235
System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +107
System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +291
System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +13
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +56
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +420
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +52
System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +173
System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +100
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27
System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +13
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +36
System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +12
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +22
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +26
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +21
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +28
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9765045
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
When you try to include the partial view using #Html.Partial("_PartialHeader_Dashboard") , MVC framework will try to load the partial views from the below locations as per the MVC conventions.
~/Views/DirectoryWithYourCurrentControllerName/
~/Views/Shared/
The framework has no idea your partial view is inside a sub directory unless you tell the framework to do so by extending the view engine and specifying the view file location(ViewLocationFormats). All you need to do is add your custom location.
You have 2 options
Call the partial view with the directory name (which is under shared)
#Html.Partial("UserDashboard/_PartialHeader_Dashboard")
Or
Use the full file path
#Html.Partial("~/Views/Shared/UserDashboard/_PartialHeader_Dashboard.cshtml")
But a better option is to consider Areas. Areas are present for logically keeping things (controllers/ views etc) together.

xero c# API not working

have copied sample xero API wrapper in C# from github. But when same code is copied into the current MVC3 project, it gives a Object reference not set to an instance of state .
the relevant code is as follows:
Home controller method:
public ActionResult Index()
{
IOAuthSession oauthSession = ServiceProvider.GetCurrentSession();
Repository repository = ServiceProvider.GetCurrentRepository();
// Can we already access an organisation??
if (oauthSession.HasValidAccessToken && repository != null && repository.Organisation != null)
{
return new RedirectResult("~/");
}
if (oauthSession is XeroApiPrivateSession)
{
throw new ApplicationException("The current private session cannot access the authorised organisation. Has the access token been revoked?");
}
// Determine the callback uri to use - this must match the domain used when the application was registerd on http://api.xero.com
var callbackUri = new UriBuilder(Request.Url.Scheme, Request.Url.Host, Request.Url.Port, Url.Action("Callback"));
// Call: GET /oauth/RequestToken
RequestToken requestToken = oauthSession.GetRequestToken(callbackUri.Uri);
// error comes here...
string authorisationUrl = oauthSession.GetUserAuthorizationUrl();
return new RedirectResult(authorisationUrl);
}
the full error is as follows:
Object reference not set to an instance of an object.
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.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
Line 45:
Line 46: // Call: GET /oauth/RequestToken
Line 47: RequestToken requestToken = oauthSession.GetRequestToken(callbackUri.Uri);
Line 48:
Line 49: string authorisationUrl = oauthSession.GetUserAuthorizationUrl();
Source File: \Xero\Xero\Xero\Xero\Controllers\HomeController.cs Line: 47
Stack Trace:
[NullReferenceException: Object reference not set to an instance of an object.]
DevDefined.OAuth.Consumer.OAuthSession.GetRequestToken(Uri callbackUri) in n:\w2\861c2b03515ac7b6\source\XeroApi\OAuth\Consumer\OAuthSession.cs:181
Xero.Controllers.HomeController.Index() in i:\Softech projects\Xero\Xero\Xero\Xero\Controllers\HomeController.cs:47
lambda_method(Closure , ControllerBase , Object[] ) +101
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +59
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +435
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +60
System.Web.Mvc.<>c__DisplayClass15.<InvokeActionMethodWithFilters>b__12() +145
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +433
System.Web.Mvc.<>c__DisplayClass17.<InvokeActionMethodWithFilters>b__14() +72
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +323
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +844
System.Web.Mvc.Controller.ExecuteCore() +130
System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +229
System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +39
System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +71
System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +44
System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +42
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +152
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.<>c__DisplayClasse.<EndProcessRequest>b__d() +38
System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +31
System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +61
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +118
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +38
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9514812
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
any help appreciated.
the aim is to connect to xero api and use its methods. if there is any working methods for C#, please inform if possible
The line throwing the exception is used for obtaining unverified request token from Xero. Without knowing much what you have done to setup the app, it appears that you have not registered your app with Xero and have not added your consumer key and secret in Web.config.
For a Xero public app, these settings are required:
<!-- Consumer Key and Secret, taken from an public/partner application registered at http://api.xero.com -->
<add key="XeroApiConsumerKey" value="xxxxxxxxxxxx"/>
<add key="XeroApiConsumerSecret" value="xxxxxxxxxxxxxxxxxxx"/>
<!-- SignatureMethod. Use 'HMAC-SHA1' for public apps, 'RSA-SHA1' for private and partner apps. -->
<add key="XeroApiSignatureMethod" value="HMAC-SHA1"/>
<!-- Xero API Endpoints
Use 'https://api.xero.com/' for public and private apps
Use 'https://api-partner.network.xero.com/' for partner apps
-->
<add key="XeroApiBaseUrl" value="https://api.xero.com/"/>
In your app setup at Xero developer website, make sure to use right domain name. For example, if you are running your app on your local host (say for testing), enter localhost in domain name field in your registered app at Xero.
If all these settings are properly made, there is no reason why it wouldn't work. You can ask me if you run into other issues.
[By the way, referring to the exception you have posted, you can always open Xero API source and find out what is line 181 of OAuthSession.cs so that you know what object is not being populated.]

MVC Web API POST Entity (500 internal server error)

I've been working on building an API for my company's website. I've got actions for all of my GETs working fine and returning JSON like I want.
I'm having problems when it comes to using POST to create new records though. I'm sending JSON to my controller. This works fine if my controller is accepting a string or object parameter, but doesn't work when it is expecting a Model.
Inside my api controller, I have this method:
[HttpPost]
public void POSTEstimate(Estimate estimate)
{
//never makes it to the first line when expecting a Model (Estimate)
}
From what I've been reading it looks like Web API should be able to deserialize the JSON that is posted automatically (and put it into my Model), but instead I always get a 500 Internal Server Error. The method works fine when I tell it to accept a string.
Is there something obvious I'm doing wrong here?
Edit: Here's the stack trace from the test page I'm using to call the API Method:
[WebException: The remote server returned an error: (500) Internal Server Error.]
System.Net.HttpWebRequest.GetResponse() +6120419
PDR.Controllers.AdminController.test() in c:\PDR\PDR\PDR\Controllers\AdminController.cs:714
lambda_method(Closure , ControllerBase , Object[] ) +96
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +17
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +205
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27
System.Web.Mvc.Async.<>c__DisplayClass42.<BeginInvokeSynchronousActionMethod>b__41() +28
System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +12
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +57
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +50
System.Web.Mvc.Async.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33() +58
System.Web.Mvc.Async.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49() +237
System.Web.Mvc.Async.<>c__DisplayClass37.<BeginInvokeActionMethodWithFilters>b__36(IAsyncResult asyncResult) +12
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +57
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +50
System.Web.Mvc.Async.<>c__DisplayClass2a.<BeginInvokeAction>b__20() +24
System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult) +126
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +57
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +45
System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult) +14
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +25
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +61
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +25
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +49
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult asyncResult) +28
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +25
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +49
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9042109
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184
Web API, like other REST frameworks, is encouraging and supporting using a POCO serializable to JSON DTO. The serialization seems to be failing.
Without the client code, which should be creating a properly formatted JSON body to POST, properly setting the content type being posted as application/json, it is hard to tell which part of the client code isn't correct.
The error being reported as an internal server error isn't helpful. The fact that your code isn't being reached, without even looking at the StackTrace, clearly indicates that the issue is occurring in framework code. The framework is expecting a properly formatted DTO, so compare the DTO being POST'd vs the DTO's definition OR construct and serialize an instance of the DTO and compare the actual strings.
I fell on something similar today, and my issue was that there were multiple possible actions in my controller that could be used by Web Api and it wasn't able to know which one to use. So in my case I used the longest form client-side and server-side for the action, instead of relying on default api route :
Router:
config.Routes.MapHttpRoute(
name: "ApiWithAction",
routeTemplate: "metadataApi/{controller}/{action}/{id}",
defaults: new {id = RouteParameter.Optional});
Ajax call:
[...]
var options = {
url: basePath + 'metadataapi/employee/FetchPage',
type: 'POST',
data: filter,
dataType: 'json'
};
return $.ajax(options);

Why am I getting a Specified Cast is not valid error?

I've developed an application with ASP.NET MVC 2, and after deploying it, I get an InvalidCastException:
Error/Exception: "Specified cast is not valid."
Stacktrace:
[InvalidCastException: Specified cast is not valid.]
System.Data.SqlClient.SqlBuffer.get_Time() +77
System.Data.SqlClient.SqlDataReader.GetTimeSpan(Int32 i) +56
Read_Question(ObjectMaterializer`1 ) +1740
System.Data.Linq.SqlClient.ObjectReader`2.MoveNext() +29
System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) +7667556
System.Linq.Enumerable.ToList(IEnumerable`1 source) +61
TestEnvironment.Managements.QuestionManager.GetquestionsByTestId(Int32 testId) in D:\ParallelMinds\Projects\TestApplication\TestEnvironment\TestEnvironment\Managements\QuestionManager.cs:131
TestEnvironment.Controllers.LoadTestController.Index(Nullable`1 testId) in D:\ParallelMinds\Projects\TestApplication\TestEnvironment\TestEnvironment\Controllers\LoadTestController.cs:31
lambda_method(ExecutionScope , ControllerBase , Object[] ) +86
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +17
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +178
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +24
System.Web.Mvc.<>c__DisplayClassd.<InvokeActionMethodWithFilters>b__a() +53
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +258
System.Web.Mvc.<>c__DisplayClassf.<InvokeActionMethodWithFilters>b__c() +20
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +193
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +300
System.Web.Mvc.Controller.ExecuteCore() +104
System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +36
System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +7
System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__4() +34
System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +21
System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +12
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +53
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +30
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +7
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8681102
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
Why am I getting this error only when I deploy the application? It works fine in my local development server, and I only get this exception on one page.
Without any more details I would guess that the table you are accessing on your deployment database is inconsistent with the table on your development database.
Maybe you have a column that is of a different type on your local machine.
Either that or there is some invalid data in the record you are retrieving in the deployment database.
The error Specified cast is not valid is encountered when one type cannot be directly cast to another.
Usually, this mistake is made when the programmer thinks they have one type, but actually have another. Take for example a textbox which has been constrained to only accept numbers. A programmer might well read the value, and later on make the mistake of expecting it to be a number
string myValue = myTextBox.Text;
// later
someComponent.ValueExpectingANumber = (int)myValue; // specified cast is not valid
in the above example, the number would have to be "Parsed" rather than cast.
It looks to me like something in your Read_Question method is filling in a field that's supposed to be SQL-compatible date or time value, and whatever the method is putting into the value is improperly formatted. The System.Data.SqlClient.SqlBuffer.get_Time() method tries to convert that value to a SQL date/time and throws an exception.
The first place I would look is in the Read_Question method.
If this happened when you published the DB, it could be that the culture is different for that server instance. For example, the differences in the english and american versions of the date.
Alternatively, if you are using DateTime.MinValue, the DateTime.MinValue differs from the range accepted by sql server; instead use the SqlDateTime object.
Can you post the code that is calling this method?
Matt

Getting strack trace error and don't understand why

I am trying to do PayPal IPN method. So I thought since I am doing asp.net mvc I can just make a method view in my controller like this
public void IPN()
{
// IPN code
}
So I tried this all on local host made my own form to post some IPN variable stuff and it worked fine. I uploaded it to my server and used the IPN simulator from paypal and it kept return a server 500 error.
So I took all the code out and basically had what you see about just a empty method in my controller. So I tried teh simulator again and it failed again with a server 500 error.
So I went and actually typed in my url to that controller method and I get this stack trace.
[NullReferenceException: Object reference not set to an instance of an object.]
site.com.Controllers.MyTestController.IPN() in MyTestController:2320
lambda_method(ExecutionScope , ControllerBase , Object[] ) +39
System.Web.Mvc.<>c__DisplayClass1.<WrapVoidAction>b__0(ControllerBase controller, Object[] parameters) +17
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +17
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +178
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +24
System.Web.Mvc.<>c__DisplayClassa.<InvokeActionMethodWithFilters>b__7() +53
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +258
System.Web.Mvc.<>c__DisplayClassc.<InvokeActionMethodWithFilters>b__9() +20
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +193
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +382
System.Web.Mvc.Controller.ExecuteCore() +123
System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +23
System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +7
System.Web.Mvc.MvcHandler.ProcessRequest(HttpContextBase httpContext) +144
System.Web.Mvc.MvcHandler.ProcessRequest(HttpContext httpContext) +54
System.Web.Mvc.MvcHandler.System.Web.IHttpHandler.ProcessRequest(HttpContext httpContext) +7
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +181
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +75
I am not sure if MyTestController:2320 is refering to line 2320(because it does not exist) or what.
Thanks
Those numbers on the right are offsets into the compiled code, so they won't point to any source code line numbers.
What I'd do in this scenario is to put some kind of logging into the code, so that I can know where in the code the exception is raised. Depending on what access you have to the server you uploaded the code to, you might be able to create a log file, or event log, etc, and use Trace statements:
Trace.WriteLine("Controllers.MyTestController.IPN(): Creating object.")
Dim o As New Object
Trace.WriteLine("Controllers.MyTestController.IPN(): Call PayPal web service.")
Call PayPal.GetAccountNumber()
Doing this would help you spot where in the code the failure is happening.
Without seeing the code we can't be sure where the NullReferenceException happening.
But, having experience setting up an IPN myself, I think you are most likely referencing a null string object. For example :
string foo = Request.Form["bar"];
foo.Trim();
//if the form collection doesn't contain a value for the key "bar" then it'll
//throw a NullReferenceException on foo.Trim()
Just make sure you are not calling any methods, properties on any object without making sure they're not null.

Categories

Resources