|
Foothill wrote: each Controller Action performs a check on the cookie
Sounds like you want an action filter[^] instead.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Is it possible to pass an object created by an authorization filter to the controller action? My authentication processing creates several objects that get used by most controller actions.
if (Object.DividedByZero == true) { Universe.Implode(); }
Meus ratio ex fortis machina. Simplicitatis de formae ac munus. -Foothill, 2016
|
|
|
|
|
Something like this[^] should work. If you add the data to the filterContext.RouteData.Values collection with a specific key, you should be able to receive it as a parameter to your action, where the parameter name matches the key.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
I ended up wrapping the Controller class in a wrapper class with Properties for the data that I needed to pass along. Problem solved.
if (Object.DividedByZero == true) { Universe.Implode(); }
Meus ratio ex fortis machina. Simplicitatis de formae ac munus. -Foothill, 2016
|
|
|
|
|
Okay, so I have made some progress but I am running into a bit of trouble. On a lot of failures, I redirect the user to the login page but the page URL is not being populated so it tries to call my login action on whatever page its on resulting in an error.
private ViewResult GetRedirectToLogin()
{
ViewResult result = new ViewResult();
result.ViewName = "~/Views/Login/Index.cshtml";
result.MasterName = "~/Views/Shared/_loginlayout.cshtml";
result.TempData = _context.Controller.TempData;
return result;
}
This has been working. Any errors with authentication are caught and the user is redirected. The problem is that the browser still thinks its on the first page so that when I click my "Login" button the server looks for a [HttpPost]Login action and returns a 404 error.
if (Object.DividedByZero == true) { Universe.Implode(); }
Meus ratio ex fortis machina. Simplicitatis de formae ac munus. -Foothill, 2016
|
|
|
|
|
How about:
private ActionResult GetRedirectToLogin()
{
return new RedirectToRouteResult(new RouteValueDictionary
{
{ "Controller", "Login" },
{ "Action", "Index" }
});
}
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
I found that one. Works like a charm. Thanks for your help on this one. I had never even looked at Action Filters before this.
if (Object.DividedByZero == true) { Universe.Implode(); }
Meus ratio ex fortis machina. Simplicitatis de formae ac munus. -Foothill, 2016
|
|
|
|
|
I have an ASP.Net application built in Visual Studio 2015 and deployed to the Azure environment. I am trying to add the capability to allow the user to reset their password. The application sends an email to the user with a link that contains a code to validate the user. After clicking on the link, the user is sent to a page that allows them to enter a new password then click a Submit button to actually change the password. This works fine in the Visual Studio environment but fails with no indication of why after being deployed to Azure. Does anyone have an idea of what might cause this?
The original page is displayed correctly and the code is validated. The process fails when the user clicks the submit button and the standard login page is displayed.
Thanks.
Phil
|
|
|
|
|
How can anyone guess with only that information Quote: fails with no indication of why You must be able to do some kind of debugging to track down the point of failure: is the token not being read? Is it being found in the database? Is a matching user record found? Is the database read or write the issue? There are numerous places in the process you can monitor to see what's going on. If nothing else, log every step along the way...
|
|
|
|
|
The token works fine and the user record is found. Those items are checked before the page is displayed that allows the user to enter a new password. It fails when it tries to submit the information. I do not have remote debugging capability so the best I can do is try to display error messages but none of them are displayed.
Code is included below:
@using Microsoft.AspNet.Identity;
@model CLCC_Browser.Models.ManageResetViewModel
@{
ViewBag.Title = "Password Reset";
Layout = "~/Views/Shared/_Layout.cshtml";
}
@ViewBag.Title.
@using (Html.BeginForm("ManageReset", "Account", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary()
@Html.HiddenFor(m => m.Token, new { @class = "form-control" })
@Html.HiddenFor(m => m.UserID, new { @class = "form-control" })
}
[AllowAnonymous]
public async Task<actionresult> ManageReset(string userName, string userId, string code)
{
IdentityResult result;
ManageResetViewModel model = new ManageResetViewModel();
var provider = new DpapiDataProtectionProvider("PokerResults");
UserManager.UserTokenProvider = new DataProtectorTokenProvider<applicationuser>(provider.Create("ResetPassword"));
UserManager.FindById(userId);
try
{
result = await UserManager.ConfirmEmailAsync(userId, testcode);
}
catch (InvalidOperationException ioe)
{
// ConfirmEmailAsync throws when the userId is not found.
ViewBag.errorMessage = ioe.Message;
return View("Error");
}
if (userId == null || code == null)
{
return View("Error");
}
ViewBag.HasLocalPassword = false;
ViewBag.UserID = userId;
model.UserName = userName;
model.UserID = userId;
model.Token = code;
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<actionresult> ManageReset(ManageResetViewModel model)
{
IdentityResult result;
var provider = new DpapiDataProtectionProvider("PokerResults");
UserManager.UserTokenProvider = new DataProtectorTokenProvider<applicationuser>(provider.Create("ResetPassword"));
string thetoken = await UserManager.UserTokenProvider.GenerateAsync("ResetPassword", UserManager,
UserManager.FindByName(model.UserName));
model.Token = thetoken;
ModelState state = ModelState["NewPassword"];
if (state != null)
{
state.Errors.Clear();
}
if (ModelState.IsValid)
{
// result = await UserManager.AddPasswordAsync(User.Identity.GetUserId(), model.NewPassword);
result = await UserManager.ResetPasswordAsync(model.UserID, thetoken, model.NewPassword);
if (result.Succeeded)
{
ModelState.AddModelError("", "Password Reset Succeeded.");
Response.Write("alert('Password Updated');");
ViewBag.Message = "Password Reset Successful";
ViewBag.ResetType = "Complete";
Session["ResetStatus"] = "Complete";
return RedirectToAction("ResetPassword", "Account", "Complete");
// return RedirectToAction("Manage", new { Message = ManageMessageId.SetPasswordSuccess });
}
else
{
ModelState.AddModelError("", "Password Update failed, User = " + model.UserID);
Response.Write("alert('Password Update failed');");
AddErrors(result);
}
}
else
{
ModelState.AddModelError("", "Password Update failed");
Response.Write("alert('Password Update failed - Invalid Model');");
}
return View(model);
}
|
|
|
|
|
Please how can I get code for encrypting and decrypting using zero distortion technique of image steganography
|
|
|
|
|
As CP is not a code-service site, your best option probably to use Google, and the second best to hire someone...
Skipper: We'll fix it.
Alex: Fix it? How you gonna fix this?
Skipper: Grit, spit and a whole lotta duct tape.
|
|
|
|
|
Hi again,
This is part of our ongoing dynamic row creation in Repeater.
By default, the first row is available.
After filling in data into the cells of the first row, user clicks the Add New Row button to add another row.
This part works fine.
The issue is that whether user enters one row or several rows, when you submit the data to the database, only one row of data is saved.
Here is the code that I am using.
Any ideas how to modify this so that no matter how many rows are created in the markup, those rows are saved to the database.
Thanks in advance.
foreach (DataRow row in table.Rows)
{
string txBoatRegNum = row.ItemArray[1] as string;
string txTaxPayerRet = row.ItemArray[2] as string;
if (txBoatRegNum != null & txTaxPayerRet != null)
{
if (string.IsNullOrEmpty(txTaxPayerRet))
{
txTaxPayerRet = "0";
}
SqlCommand aircmd = new SqlCommand("sp_savetInfo", conn);
aircmd.CommandType = CommandType.StoredProcedure;
aircmd.Parameters.AddWithValue("@pid", accountnumber.Text);
aircmd.Parameters.AddWithValue("@eID", Request["pageId"]);
aircmd.Parameters.AddWithValue("@txYr", txtTaxYr.Text);
aircmd.Parameters.AddWithValue("@regno", txBoatRegNum);
aircmd.Parameters.Add("@txretval", SqlDbType.Money).Value = decimal.Parse(txTaxPayerRet);
aircmd.ExecuteNonQuery();
lblResult.ForeColor = System.Drawing.Color.Green;
lblResult.Text = "Thank you! <br>You have successfully completed the form.";
lblResult.ForeColor = System.Drawing.Color.Red;
lblResult.Text = "Your form failed to save, please try again.";
}
}
|
|
|
|
|
What happens when you step through the code in the debugger?
|
|
|
|
|
You need to debug it and see what is happening. We don't know what table.Rows is or what is in it so there is little we can do to help.
There are two kinds of people in the world: those who can extrapolate from incomplete data.
There are only 10 types of people in the world, those who understand binary and those who don't.
|
|
|
|
|
I wasn't completely sure which forum to put this in, ASP or JavaScript. Feel free to move it if it's not the appropriate spot.
I have a simple web application where the user inputs three integers into a form and receives the sum as a result.
My question is this: I'd like to have the actual sum value not appear until the user has Submitted. Meaning, when the page is opened up, the ViewBag just displays nothing. And then after submission, the ViewBag content appears. Is it possible for me to do this with the current code I have?
I'm aware this will probably require a JavaScript function. I just don't have very much experience integrating JS with C#.
View:
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<!-- HTML form with "Post" method initiated. -->
<form action="" method="post">
Enter the 1st Number: <input id="firstInt" name="firstInt" type="text" value="0" /><br />
Enter the 2nd Number: <input id="secondInt" name="secondInt" type="text" value="0" /><br />
Enter the 3rd Number: <input id="thirdInt" name="thirdInt" type="text" value="0" /><br />
<input id="Submit" type="submit" value="submit" />
<input id="Reset" type="reset" value="reset" /><br /><br />
Sum = @ViewBag.result
</form>
Controller:
public class HomeController : Controller
{
public ActionResult Index(int firstInt = 0, int secondInt = 0, int thirdInt = 0)
{
int sum = firstInt + secondInt + thirdInt;
ViewBag.result = sum;
return View();
}
}
modified 8-Oct-17 22:58pm.
|
|
|
|
|
Controller:
public ActionResult Index(int? firstInt = null, int? secondInt = null, int? thirdInt = null)
{
ViewBag.result = firstInt + secondInt + thirdInt;
return View();
} View:
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<form action="" method="post">
Enter the 1st Number: <input id="firstInt" name="firstInt" type="text" value="0" /><br />
Enter the 2nd Number: <input id="secondInt" name="secondInt" type="text" value="0" /><br />
Enter the 3rd Number: <input id="thirdInt" name="thirdInt" type="text" value="0" /><br />
<input id="Submit" type="submit" value="submit" />
<input id="Reset" type="reset" value="reset" />
@if (ViewBag.result != null)
{
<p>Sum = @ViewBag.result</p>
}
</form>
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
I have a GridView with a buttonfield column that I am using to edit and save the value of records. The problem I am having is that in the Grid's Row Command event I want to change the button's text from "Edit" to "Save" but my code below doesn't work. Can anyone see what I'm doing wrong?
HTML:
<asp:GridView ID="gvProducts" CssClass="gvOrders" Width="560px" PagerStyle-CssClass="pager" OnRowCommand="gvProducts_RowCommand" HeaderStyle-CssClass="header" RowStyle-CssClass="rows" AllowPaging="true" AutoGenerateColumns="false" runat="server" DataSourceID="ObjectDataSource1" AllowSorting="True">
<Columns>
<asp:buttonfield buttontype="Button" HeaderStyle-BackColor="Transparent" commandname="Edit" headertext="Edit" text="Edit"/>
<asp:buttonfield buttontype="Button" HeaderStyle-BackColor="Transparent" commandname="Delete" headertext="Delete" text="Delete"/>
<asp:BoundField HeaderText="Product ID" DataField="ProductID" SortExpression="ProductID" />
<asp:BoundField HeaderText="Units In Stock" DataField="UnitsInStock" SortExpression="UnitsInStock" />
<asp:BoundField HeaderText="Units On Order" DataField="UnitsOnOrder" SortExpression="UnitsOnOrder" />
<asp:BoundField HeaderText="Reorder Level" DataField="ReorderLevel" SortExpression="ReorderLevel" />
</Columns>
</asp:GridView>
Code behind:
protected void gvProducts_RowCommand(object sender, GridViewCommandEventArgs e)
{
switch (e.CommandName)
{
case "Edit":
int index = Convert.ToInt32(e.CommandArgument);
Button myButton = null;
myButton = (Button)gvProducts.Rows[index].Cells[0].Controls[0];
myButton.Text = "Save";
return;
case "Delete":
return;
default:
return;
}
}
|
|
|
|
|
i saw a article that global.asax is not there in asp.net core rather a concept called middleware there. i just like to know where global.asax has been removed from asp.net core and why middleware comes in core ?
what kind of advantages is there in middleware ?
if anyone knows the reason please guide me. thanks
|
|
|
|
|
Typically you need to consider reading at why did Microsoft want to shift from a bloated global handler, to a microservice-like as-needed middleware structure for the startup handler. You can start here, ASP.NET Core Middleware | Microsoft Docs
Secondly, if you have used global.asax, you know that it is tightly packed with the services that ASP.NET provides, everything is already there, it doesn't matter whether you handle it or not. Almost everything is loaded, unless you ignore importing and loading the assembly. Whereas in the middleware, you load items and attach them to the application. You remove, or add how things go around. The best benefit being, you can rearrange them as needed and you can even add your own custom middleware before ASP.NET Core's middleware — which I am not sure was allowed in global.asax.
Finally, since the framework was written to be cross-platform and thus it had to be written in a way that it can reflect the design pattern for such projects.
Quote: what kind of advantages is there in middleware ?
Also, the term middleware is just a term used for something can acts in the middle. It is nothing new, or special. It just means, that you can now shift the modules, include more, change the sequence, block a few modules to be loaded (on demand) and much more.
You should consider tweaking around a bit with the Startup class in ASP.NET Core.
The sh*t I complain about
It's like there ain't a cloud in the sky and it's raining out - Eminem
~! Firewall !~
|
|
|
|
|
Can someone point me in the right direction on how to do the following?
I need to create a small desktop application that uses FileSystemWatcher to look for file creation. When a file has been detected, it uploads the file to a server (Web API). So far so good.
Here comes the problem: The file(s) need to attach themselves to the 'page' the current user is on.
A user creates a 'New Page' on our website, fills in some information and then imports files that our FileSystemWatcher detects. Somehow the Web API need to find what session the user is on and attach the files to this session and then display the files/images on the current 'page'.
My idea is to add another cell to the user table in the database called "CurrentSession", that holds a uniqueidentifier (pointing towards the PageId). But this Id needs to be cleared if the user leaves the page, closes the browser, disconnects, log-out and so on. It's vital that the files do not attach themselves to the wrong page.
Am I over thinking this? Or is there a better way to achieve this?
|
|
|
|
|
I am not sure how feasible clearing Id would be..
But I think, you can definitely maintain the "CurrentSession" unique identifier on client (website page) as well and send this along and validate with the one stored in database. This way you do not need to take care of different ways the user is moving away.
hope this helps..
|
|
|
|
|
The problem is that the files need to go to a specific page and not a specific user.
A user can have thousand of pages, that's why the files should only be transferred IF the user is on a specific page. If they are doing anything else on the website, then the CurrentSession should be null, and the file transfer application will inform the user about it.
So the fail-safe is that if there's no active 'Page' on the customer that is trying to upload files, the application will inform the customer to go and create it and be Active on the Page.
Guess this has to be done by using a service to check for user activity or something...
|
|
|
|
|
ZilverZtream wrote: Or is there a better way to achieve this?
Let the user select the files to upload from within the website. It's the only way to be sure they're attached to the page the user is editing.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
That would have been nice.. the problem is that the device(s) the client use for image/file -transfers, usually save the files with things like guid names in folders that can contain thousand of other files.
For the user to select the file(s) (between 4-30 files) the device just transferred, in a folder with 1000's of other files with obscure file names, will probably not be ideal. Seeing how many clients are old and selecting the wrong file could be a disaster.
The files are not the issue here, the issue is the "page". The thing is, one user can easily have 20,000 pages. That's why I wanted a solution that can check the CurrentID of the page the user is on.
But agreed, the easiest solution would have been to have a File Upload button on the page, and have the user select the files, but the way the systems are setup, that'll never work.
|
|
|
|