Menu
  • HOME
  • TAGS

Why does HasChildNodes in MvcSiteMap v4 trigger HandleUnauthorizedRequest for each unauthorized node?

Tag: asp.net-mvc-4,mvcsitemap,mvcsitemapprovider

I'm upgrading from v3 to v4 of MvcSiteMap, and it seems just using the property Html.MvcSiteMap().SiteMap.CurrentNode.HasChildNodes triggers a hit on HandleUnauthorizedRequest in AuthorizeAttribute for every unathorized child node in the list.

  1. Why should this happen? I would expect HandleUnauthorizedRequest to be triggered for a separate http request, not just interrogating whether a node exists.

  2. What is the best way to distinguish between a 'genuine' unauthorized http request and simply checking an unauthorized sitemap node? My best guess so far is to check whether the controller and action match, but it seems a little unnecessary:

    protected override void HandleUnauthorizedRequest(System.Web.Mvc.AuthorizationContext filterContext)
    {
        if (filterContext.HttpContext.Request.IsAuthenticated)
        {
            var httpRouteData = ((MvcHandler)filterContext.HttpContext.CurrentHandler).RequestContext.RouteData;
            var filterRouteData = filterContext.RequestContext.RouteData;
    
            var isHttpRequestUnauth = (httpRouteData.Values["Controller"] == filterRouteData.Values["Controller"] &&
                httpRouteData.Values["Action"] == filterRouteData.Values["Action"]);
    
            if (isHttpRequestUnauth)
                throw new System.Web.HttpException(403, string.Format("Access denied for path '{0}'. ", filterContext.HttpContext.Request.RawUrl));
            else
                base.HandleUnauthorizedRequest(filterContext);
        }
        else
        {
            base.HandleUnauthorizedRequest(filterContext);
        }
    }
    

Best How To :

HandleUnauthorizedRequest is only called by the MVC AuthorizeAttribute in the case where the authorization check fails. It is meant only for setting the handler of the request, not actually to provide the check whether the user is authorized. That said, MvcSiteMapProvider doesn't call HandleUnauthorizedRequest directly - it calls OnAuthorization.

The default implementation of AuthorizeAttribute.OnAuthorization makes the check already, so I am unsure what you hope to accomplish by comparing the controller and action again in HandleUnauthorizedRequest since unauthorized users cannot reach that path unless you override the implementation of OnAuthorization as well (or you rely on output caching entirely).

Anyway, to answer your question, in v3 and early revisions of v4 MvcSiteMapProvider used Reflection.Emit to generate a class on the fly that inherited from AuthorizeAttribute or any subclass of AuthorizeAttribute as described in this post. The subclass added public access to the AuthorizeCore method so it could be called by MvcSiteMapProvider. However, that approach had performance issues and also could not be used with sealed overloads of AuthorizeAttribute.

Since then, it has evolved to use the one and only public member of AuthorizeAttribute - OnAuthorization - to do the check. The author of the above post made an error in his assertion that Reflection.Emit was the only way it could be done because he didn't take into account using a subclass of HttpContext.Response that overrides the output caching members. We compromised on using the result of HandleUnauthorizedAttribute (setting the filterContext.Result property to a non-null value) as the way to determine whether or not the security check works.

Unfortunately, there is not a way to make a solution that works 100% of the time because AuthorizeAttribute was only designed to be used in the context of a request for the current page, but this is the solution that we compromised on because it requires the least amount of code to maintain, performs the best, and uses direct method calls instead of workarounds. If you use the typical method of overloading AuthorizeCore for custom logic, it will work perfectly. On the other hand, if you overload OnAuthorization or HandleUnauthorizedRequest, you need to ensure that the filterRequest.Result property is set to non-null for unauthorized and null for authorized.

MVC - How to render a 'a href' link in a View that's been stored in a database?

asp.net-mvc,asp.net-mvc-4,model-view-controller

Try this: <h4>@Html.Raw(Model.HomePageVM.AboutUsDescOne)</h4> Use this helper with caution though. If a user can edit this block of HTML then you might be making yourself vulnerable to an XSS attack: Text output will generally be HTML encoded. Using Html.Raw allows you to output text containing html elements to the client, and...

Angularjs ng-show doesn't work with Viewbag

angularjs,asp.net-mvc-4

Try this: <div ng-show="'@(ViewBag.AllowExport)'"> <a href="JavaScript:void(0);">Export</a> </div> ...

Call back from server to client

c#,asp.net,asp.net-mvc,asp.net-mvc-4

You have to write an ActionResult that progressively write result to the response. so you can show the user some data in every foreach loop iteration. I have written a simple ActionResult that writes a number every 2 seconds: public class ProgressiveResult : ActionResult { public override void ExecuteResult(ControllerContext context)...

Conflicted with the REFERENCE constraint. How to solve this?

asp.net-mvc-4,nhibernate

Judging by that error, your repository is trying to delete the a user from its table but that user is referenced in another table (dbo.Invoices). So you are seeing a foreign key constraint error where you are trying to delete a record who's primary key is referenced in another table...

Need to Close the div in if condition MVC View

asp.net-mvc,asp.net-mvc-4

I think you need something like this, run two loops one for total and one for two items. so this condition of loose close elements will not occur. @for (int count = 0; count <= ViewBag.modal.Count; count++) { <div class="Class1"> @for (int counter = 0; counter < 2 && (count...

Prevent page refresh on submit button click

asp.net-mvc-4

In the server-side validation ,the page must be submitted via a postback to be validated on the server and if the model data is not valid then the server sends a response back to the client. With client-side validation, the input data is checked as soon as they are submitted,...

Retrieve all data from the database got the second row same with the first row

c#,mysql,asp.net-mvc-4

Your error occurs because you declare just one instance of context, and the keep updating its UserName in the while loop (inside the while loop you just add another reference of it to the collection) You need to declare a new instance inside the loop while (reader.Read()) { UserContext context...

A specified Include path is not valid. The EntityType '*Propiedad' does not declare a navigation property with the name 'Nombre'

c#,asp.net-mvc,entity-framework,asp.net-mvc-4,repository-pattern

Include is made to eagerly load navigation properties, meaning any property that is, in fact, another related entity. Since Nombre is a string, you do not need to include it: it is part of the entity that is returned from the database call. If Nombre were of a class representing...

MvcSiteMapProvider - Enhanced bootstrap dropdown menu

c#,twitter-bootstrap,asp.net-mvc-5,mvcsitemapprovider,mvcsitemap

node.Descendants should be node.Children Learn the difference on Descendants and Children here, CSS Child vs Descendant selectors (Never mind the post beeing about CSS, this is a generic pattern)...

MVC 4 - pass parameter to controller on button click

asp.net-mvc-4

The input buttons have a value. You can detect the value of the input button at the controller. <input type="submit" value="submitbutton"> <input type="submit" value="savebutton"> ...

Rendering “~/bundles/jqueryval”

c#,asp.net-mvc,asp.net-mvc-4,razor

You need to declare the section within your "master page": @RenderSection("Scripts", false) Probably the best idea to include this in the head tag. Otherwise it doesn't know what to do with your Scripts section defined in your child view. The second parameter, which I've set to false is whether or...

How to consume multipart/form data request in C# mvc 4 webservice

c#,asp.net-mvc,web-services,wcf,asp.net-mvc-4

Check Request.Files variable. foreach (string file in Request.Files) { var postedFile = Request.Files[file]; postedFile.SaveAs(Server.MapPath("~/UploadedFiles") + pelicula.Id); } ...

Return to the same view when no image is selected

asp.net-mvc-4,razor,json.net,entity-framework-5,c#-5.0

Add a ModelState error and return the view (otherwise redirect), for example if (isSavedSuccessfully) { return Redirect(Url.Action("Edit", "Account") + "#tabs-2"); } else { ModelState.AddModelError("Image", "your message"); return View(user); } ...

C# mvc4 - direct URL to controller

c#,asp.net-mvc-4,url,redirect

You might have forgotten to specify name of the controller in Html.ActionLink() parameter. Try Html.ActionLink("actionname","controllername");

Add XElement dynamically using loop in MVC 4?

c#,xml,asp.net-mvc-4,for-loop

This is the complete code [HttpPost] public ActionResult SURV_Answer_Submit(List<AnswerQuestionViewModel> viewmodel, int Survey_ID, string Language) { if (ModelState.IsValid) { var query = from r in db.SURV_Question_Ext_Model.ToList() join s in db.SURV_Question_Model on r.Qext_Question_ID equals s.Question_ID where s.Question_Survey_ID == Survey_ID && r.Qext_Language == Language orderby s.Question_Position ascending select new { r, s };...

get roles attribute of controller in OnActionExecuting in mvc

c#,asp.net-mvc,asp.net-mvc-4,actionfilterattribute

You can use GetFilterAttributes method of ActionDescriptor or ControllerDescriptor: protected override void OnActionExecuting(ActionExecutingContext filterContext) { var filters = new List<FilterAttribute>(); filters.AddRange(filterContext.ActionDescriptor.GetFilterAttributes(false)); filters.AddRange(filterContext.ActionDescriptor.ControllerDescriptor.GetFilterAttributes(false)); var roles = filters.OfType<AuthorizeAttribute>().Select(f => f.Roles); ... } ...

Why is my View not displaying value of ViewBag?

c#,asp.net,asp.net-mvc,asp.net-mvc-4,razor

ViewBag is used when returning a view, not when redirecting to another action. Basically it doesn't persist across separate requests. Try using TempData instead: TempData["Tag"] = post.SelectedTag.ToString(); and in the view: <p><strong>Tag: @TempData["Tag"]</strong></p> ...

Use “Contains” to match part of string in lambda expression

c#,jquery,asp.net-mvc-4,lambda

I would search your initial items (before you made the into a list of TextValuePair) then you could do something like IEnumerable<Item> items = originalItemsList; switch (source) { case "1": // or whatever this should be items = items.Where(x => x.ItemNumber.IndexOf(data, StringComparison.InvariantCultureIgnoreCase) > -1); break; case "2": // or whatever...

C# entity framework MVC second run error

entity-framework,asp.net-mvc-4,localdb

Your initialiser is using the DropCreateDatabaseAlways class which, as it suggests, drops that database every time the application is initialised. Instead perhaps you could use CreateDatabaseIfNotExists or DropCreateDatabaseIfModelChanges: public class ComponentDbInitialize : CreateDatabaseIfNotExists<ComputerContext> { } ...

ApplicationUser ICollection member not being saved in DB

c#,.net,entity-framework,asp.net-mvc-4,asp.net-mvc-5

You need to model your collection items. You could go many to many or one to many. // many to many public class Interest { public int InterestId { get; set; } public string InterestDesc { get; set; } // field can't match class name } // one to many...

C# Using Bool, how to check a double is truly divisible by another number? [duplicate]

c#,asp.net-mvc-4

You can use the %-operator: bool isDivisible = 1115 % 100 == 0; The % operator computes the remainder after dividing its first operand by its second. All numeric types have predefined remainder operators. ...

Display value of a textbox inside another textbox using AngularJs on button click

angularjs,asp.net-mvc-4

in your controller do , $scope.myFunction = function () { $scope.display = $scope.type; } in your html you have to change onclick to ng-click, <input type="button" value="button" ng-click="myFunction()" /> see this plunk for example, http://plnkr.co/edit/c5Ho1jlixwZFx7pLFm9D?p=preview...

startIndex cannot be larger than length of string

c#,entity-framework,asp.net-mvc-4

You should have code in following way - string newFilenameExtension = Path.GetExtension("Sample".Trim()); string extn = string.Empty; if (!String.IsNullOrWhiteSpace(newFilenameExtension)) { extn = newFilenameExtension.Substring(1); } if(!String.IsNullOrWhiteSpace(extn)) { // Use extn here } ...

MVC Push notification from server to client side

asp.net-mvc-4,push-notification

You can use SignalR : $.connection.hub.start().done(function () { $('#sendmessage').click(function () { // Call the Send method on the hub. chat.server.send($('#displayname').val(), $('#message').val()); // Clear text box and reset focus for next comment. $('#message').val('').focus(); }); }); use more info: tutorial...

check for value null on razor syntax

c#,asp.net-mvc,asp.net-mvc-3,asp.net-mvc-4,razor

try this: @{ if (propiedadesFormularioDetalle != null) { <div class="panel panel-default"> <div class="panel-heading">Propiedades adicionales</div> <div class="panel-body"> <dl class="dl-horizontal"> foreach (KeyValuePair<string, string> propiedad in propiedadesFormularioDetalle) { <dt> Html.DisplayName(propiedad.Key) </dt> <dd> Html.DisplayFor(prop => propiedad.Value) </dd> } </dl> </div> } </div> } ...

Dynamically adding controls in MVC4

asp.net-mvc,asp.net-mvc-4

You can create a editor template and pass the control list as model to the template and in the template you can iterate that list to generate the control. As i have shown below. 1->Create a class for Control Information. public class ControlInfo { public string ControlType { get; set;...

How to get started with Visual studio 2012

c#,asp.net-mvc,asp.net-mvc-3,asp.net-mvc-4,visual-studio-2012

Download this book "Microsoft ASP.NET 4 Step By Step" by George Shepherd.I found it very helpful.It will address all the issues you raised here.Thank you.

How to bind anonymous type to viewModel in ASP.NET-MVC

c#,asp.net-mvc,asp.net-mvc-4

Dont leave your select query anonymus, just pass your select with viewModed like var v = (from pd in ge.Costs join od in ge.Services on pd.ServiceId equals od.ServiceId join ct in ge.ServiceTypes on pd.ServiceTypeId equals ct.ServiceTypeId where pd.ServiceTypeId.Equals(2) select new costViewModel() { CostId = pd.CostId, serviceName = od.serviceName, ServiceTypeValue =...

Why does my MVC binding stop working when I assign a nested model to a variable?

c#,asp.net-mvc,asp.net-mvc-4,razor

If you inspect the html you are generating you will see that they are not the same. Your first code block generates html like <input name="NestedModel[0].Id" id="NestedModel_0__Id" .../> <input name="NestedModel[1].Id" id="NestedModel_1__Id" .../> The second one will generate html like <input name="nestedModel.Id" id="nestedModel_Id" .../> <input name="nestedModel.Id" id="nestedModel_Id" .../> The second generates...

How can I bind a list model which contains a complex type in MVC4?

c#,asp.net-mvc,asp.net-mvc-4

You can use javascript to handle onsubmit event and merge data from those two fields into one that will be parsed as DateTime. Do you need some code to see how it could be done?

Use Bearer Token Authentication for API and OpenId authentication for MVC on the same application project

c#,asp.net-mvc-4,oauth-2.0,openid,identityserver3

Ok, I found some information on the following post https://github.com/IdentityServer/IdentityServer3/issues/487 The github repo that implements the concepts discussed in the link can be found here https://github.com/B3nCr/IdentityServer-Sample/blob/master/B3nCr.Communication/Startup.cs Basically you need to map the api url to a different configuration using app.Map(). In my case, I changed my startup file to look...

How to Implement Dependent Dropdownlist in MVC4 Razor and using SQL server also

sql-server,asp.net-mvc-4,razor

Note : As per your requirement you need to show country name when user selects the state then why you need dropdownlist for country ?? it is better to use a label for that. For you requirement first you have to maintain a table which stores country and it's state...

How to add validators for @Html.TextBox() without model

asp.net-mvc,asp.net-mvc-4

Add data-val and data-val-required attribute for Html.TextBox() as shown below. <script src="~/Scripts/jquery-1.10.2.min.js"></script> <script src="~/Scripts/jquery.validate.min.js"></script> <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script> @using (Html.BeginForm("","")) { @Html.ValidationSummary() @Html.TextBox("bill_address", null, new { @class = "form-control valid", @data_val = "true", @data_val_required = "Billing Address is required" }) <input type="submit" value="Click"...

Unable to make parent li active on click of child li with bootstrap in mvc4

c#,asp.net,asp.net-mvc-4,c#-4.0

There are 2 things to do, one is make the active selection when user clicks and the other is save this selection after the page refreshs right? If you want to make li selected after the page refresh you need to save this state somewhere. You can save it in...

mvc 4 custom format validator does not show error and allows the form to submit

asp.net-mvc,validation,asp.net-mvc-4

In order to get client side validation, your attribute must implement IClientValidatable and you must include a client side script that adds a method to the client side $.validator object. This article THE COMPLETE GUIDE TO VALIDATION IN ASP.NET MVC 3 gives some good examples of how to implement it....

How do you send data to controller with ajax.beginform?

ajax,asp.net-mvc-4,razor,model-view-controller,model

To make you understand how AJAX FORM works, I created below code - Lets say our model - public class Sale { public string SaleOwner { get; set; } public virtual Account Account { get; set; } } public class Account { public string Name { get; set; } }...

Custom Data Annotation and MVC Helper

c#,asp.net-mvc,asp.net-mvc-4

You're gonna need to extend the HtmlHelper class with the following: public static MvcHtmlString HelpTextFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expr) { var memberExpr = expr.Body as MemberExpression; if (memberExpr != null) { var helpAttr = memberExpr.Member.GetCustomAttributes(false).OfType<HelpTextAttribute>().SingleOrDefault(); if (helpAttr != null) return new MvcHtmlString(@"<span class=""help"">" + helpAttr.Text + "</span>"); }...

Setting up routing when RemoteAttribute specifies AdditionalFields

c#,asp.net,asp.net-mvc,asp.net-mvc-4

When it receives a query such as /Validation/IsUserNameAvailable?userName=BOB&UserID=, MVC's model binder is confused because it does not know how to handle null/empty string params. Just change the param to an int and cast as necessary for your helper method: public JsonResult IsUserNameAvailable(string userName, int UserId) { var users = new...

Mvc Remote Attribute is sending “undefined” in query string

c#,asp.net,asp.net-mvc,asp.net-mvc-4

You need to add @Html.HiddenFor(m=>m.UserId) at the view so that the binder will bind it to the remote validation controller or otherwise there is no value to bind ...

Binding my view model to a view causes all check boxes to be checked

c#,asp.net,asp.net-mvc,asp.net-mvc-4,razor

In your view, remove <input type="checkbox" value="" checked="checked"/> Allow Access Because of checked="checked", this will always print out a checked checkbox....

404 when converting asp.net mvc app to angularjs

c#,asp.net,asp.net-mvc,angularjs,asp.net-mvc-4

MVC pattern means the controller takes requests and renders views. You are trying to bypass that and the Views/web.config prevents that. You can either render your view via the Controller (MVC-style), or configure a section of your app to serve static files ...

ASP .Net MVC get decorated roles for unathorized request

c#,asp.net,asp.net-mvc,asp.net-mvc-4

The AuthorizeAttribute has a property called Roles that you should be able to check to get the information you want. As mentioned by @EricFunkenbusch you can assume that the user is not in any of those roles. https://msdn.microsoft.com/en-us/library/dd460323(v=vs.118).aspx...

Form Post Not working While Submission

c#,asp.net,asp.net-mvc,asp.net-mvc-4

You have to fix your connection. But incorrect connection string may have different causes. Try to connect to your database with Server Explorer in Visual Studio then select your database and press F4 (Properties). You can see the correct connection string there. Put it in connection string in your web.config.

Using Bootstrap 3 DateTimePicker in ASP.NET MVC Project

jquery,asp.net-mvc,twitter-bootstrap,asp.net-mvc-4,bootstrap-datetimepicker

The easiest way in MVC with bootstrap would be to set the properties in your model with DataAnnotations. Here is a link that should help you. Using Data Annotations for Model Validation [DisplayName("Owners Date of Birth:")] Will display in the @Html.LabelFor and this will be the label for your field....

Exact need of jquery.validate.js

jquery,asp.net-mvc-4,jquery-validate

jQuery Validate is just an addon for jQuery you could use. So you still got to write the validation yourself, even though jQuery Validate makes a lot of things easier. Here is a documentation on the plugin you should check out, to use it for your needs....

Cannot get data using LINQ in MVC

c#,asp.net-mvc,linq,asp.net-mvc-4

Ensure term matches the case of the data. As all the data is loaded (.ToList() in the DAL), the .Where clause uses .Net comparison rather than SQL comparison: var vehicle = _service.GetAll().Where(c => c.Name.StartsWith(term, StringComparison.OrdinalIgnoreCase)... If, in the future, you want to change this to Contains, you can add an...

Why mozilla changes the characters when i use the .net mvc statement redirect?

c#,asp.net-mvc-4,redirect,mozilla

%E2%80%8B is a URL-encoded, UTF-8 encoded ZERO-WIDTH SPACE character. You likely have one hiding in your application setting file for the ProActiveOffice-URL value. It was maybe pasted in that way, if you copied the URL from somewhere.

MVC 5 OWIN login with claims and AntiforgeryToken. Do I miss a ClaimsIdentity provider?

asp.net-mvc,asp.net-mvc-4,razor,asp.net-mvc-5,claims-based-identity

Your claim identity does not have ClaimTypes.NameIdentifier, you should add more into claim array: var claims = new List<Claim> { new Claim(ClaimTypes.Name, "Brock"), new Claim(ClaimTypes.Email, "[email protected]"), new Claim(ClaimTypes.NameIdentifier, "userId"), //should be userid }; To map the information to Claim for more corrective: ClaimTypes.Name => map to username ClaimTypes.NameIdentifier => map...

How to store a string in xml file and use it in _Layout in MVC

c#,xml,asp.net-mvc,asp.net-mvc-4

Sourced: from this link The web.config (or app.config) is a great place to store custom strings: in web.config: <appSettings> <add key="message" value="Hello, World!" /> </appSettings> in cs: string str = ConfigurationSettings.AppSettings["message"].toString(); ...

Partial View's checkbox state not returned to controller

c#,asp.net,asp.net-mvc,asp.net-mvc-4,razor

asp.net MVC model binding can only bind to one model. To solve your issue you would simply need to create a base class that all your models, that may use a FacilityList , would derive from. Like so: public class FacilityViewModel { public Dictionary<string, bool> FacilityList { get; set; }...