Sir, my question was bit different. i am trying to know how asp.net mvc engine understand now user need to redirect to login page? if login controller name would be different then how asp.net mvc understand it ? where this binding done in default project when we create a default project from IDE? i believe there must be a place where we mention that login page should come if user is not signed in when access any protected resource. please share knowledge if you know. thanks
Mou_kol
Posts
-
ASP.Net MVC: How unauthorize access redirect user to login page -
ASP.Net MVC: How unauthorize access redirect user to login pagesuppose i am developing a site with ASP.Net MVC core. i have created a empty project where i add two controller. one is Home and login controller. Home controller's index action is not protected by Authorized attribute but Home controller's product action is protected. when user try to access product action then user should be redirected to login page if not signed in. so tell me how to setup project in classic mvc or mvc core where i will mention that user should be redirected to login page if user is not signed in. i will not use identity rather i will check user credentials from db using ado.net. please guide me step wise that what i need to follow. Thanks
-
Rest API always return 401 status codei am looking for c# related call.
-
Rest API always return 401 status codeI am working with Nasdaq Fund Network Data Service first time. i am calling their one of the API where passing user id,pwd and access key but always getting 401 status code. i am not able to figure out what is wrong in my http call. please some one have a look at the code and tell me where i made the mistake for which i am getting 401 status code instead of right response. here is my sample code where i could not share actual credentials and access key.
string url = "https://nfn.nasdaq.com/servicecall/tempsession";
Uri u = new Uri(url);string username = "test1";
string password = "test1";
string accessKey = "my key";var payload = new Dictionary
{
{"username", username},
{"password", password},
{ "accesskey", accessKey}
};string strPayload = JsonConvert.SerializeObject(payload);
HttpContent c = new StringContent(strPayload, Encoding.UTF8, "application/x-www-form-urlencoded");var response = string.Empty;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11;
using (var client = new HttpClient())
{
//client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessKey);
//client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Authorization", "Bearer " + accessKey);HttpRequestMessage request = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = u,
Content = c
};var result = client.SendAsync(request).Result;
if (result.IsSuccessStatusCode)
{
response = result.StatusCode.ToString();
}
} -
ASP.NET Core MVC: How to secure token when passing with urlThanks for guide line.
-
ASP.NET Core MVC: How to secure token when passing with urli got a application developed with asp.net core mvc where token is always passed with url. it seems if we pass token with each url then it is not secure way. so any time any other user can get url and appear before server as right user. our token life is 24 hours. sample url looks like http://localhost:48000/ACX/Default/Login?token=8kzRLdW8lQVIS0MrtlqdZJbmz9p22l33u1wspGOmLgCgEy2MG5XZ0JG1ovVZGiNX7KpAfBVn3[^]
This code is generating the token which would valid up to 24 hours:
public IActionResult Login([FromBody]LoginModel user)
{
if (user == null)
{
return BadRequest("Invalid request");
}if (user.UserName == "johncitizen" && user.Password == "abc@123") { var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("KeyForSignInSecret@1234")); var signinCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256); var tokeOptions = new JwtSecurityToken( issuer: "http://localhost:2000", audience: "http://localhost:2000", claims: new List(), expires: DateTime.Now.AddMinutes(1440), // valid till 24 hours signingCredentials: signinCredentials ); var tokenString = new JwtSecurityTokenHandler().WriteToken(tokeOptions); return Ok(new { Token = tokenString }); } else { return Unauthorized(); }
}
What can we do as a result token would be secure passing through URL? I want to change flow bit in such a way that if another user copy and paste the same URL, then he will not be able to access protected resource. So how to achieve and secure long life token? Please guide me with approach in details. Thanks
-
ASP.Net MVC and querySelectorAll usageSir, thank you so much for reply.
-
ASP.Net MVC and querySelectorAll usagePlease see the code.
using (Html.BeginForm("Login", "Default", new { ReturnUrl = ViewBag.ReturnUrl, data = Request.QueryString["data"] }, FormMethod.Post,
new
{
id = "idtest1",
onsubmit = "this.querySelectorAll('button').forEach(i => i.disabled = false)",
@class = "form-signin",
role = "form"
}))
{}
specially see this line which is not clear to me. onsubmit = "this.querySelectorAll('button').forEach(i => i.disabled = false)", in the above code BeginForm html helper has been used to render form at runtime. what will happen when form will be submitted ? what this line will do when form submit ? onsubmit = "this.querySelectorAll('button').forEach(i => i.disabled = false)", please help me to understand this JavaScript code objective when form submit. Thanks
-
Facing problem when calling store procedure from c# codeSir there was a problem in SP code. now everything is working fine after fixing. Thanks
-
Facing problem when calling store procedure from c# codeI have store procedure which insert and update data and at the end it return multiple data. i am using SQL helper utility class to call store procedure. i use
ds = await SqlHelper.ExecuteDatasetAsync(ConnectionManager.GetConnectionString(), CommandType.StoredProcedure, "USP_InsertBMAsLineItem", spParameter);
execution stuck at this line. i am not able to figure out where i made the mistake. when i execute SP from SSMS then everything goes fine. please see my store procedure and c# code. tell me where i made the mistake.
ALTER PROC USP_InsertBMAsLineItem
(
@TickerID VARCHAR(20),
@CommaSeparatedItems VARCHAR(MAX),
@UserID VARCHAR(20)
)
AS
BEGIN
Declare @Start INT, @Count INT,@MaxOrder INT
SET @Start=1
SET @Count=1
SET @MaxOrder=0BEGIN TRY BEGIN TRAN DROP TABLE IF EXISTS #Tmpdata CREATE TABLE #Tmpdata ( ID INT Identity, LineItem VARCHAR(MAX) ) INSERT INTO #Tmpdata(LineItem) ( SELECT value as LineItem FROM STRING\_SPLIT(@CommaSeparatedItems, ',') ) MERGE INTO TblLineItemTemplate Trg USING ( SELECT value as LineItem FROM STRING\_SPLIT(@CommaSeparatedItems, ',') ) AS Src ON UPPER(TRIM(Trg.LineItem)) = UPPER(TRIM(Src.LineItem)) AND Trg.TickerID = @TickerID WHEN MATCHED THEN UPDATE SET Trg.Action = 'U', ModifiedBy=@UserID WHEN NOT MATCHED THEN INSERT ( TickerID, LineItem, Action, InsertedOn, InsertedBy ) VALUES (TRIM(@TickerID), TRIM(Src.LineItem), 'I', GETDATE(),@UserID); SELECT @Start=MIN(ID) FROM #Tmpdata SELECT @Count=MAX(ID) FROM #Tmpdata WHILE (@Start<=@Count) BEGIN IF NOT EXISTS(SELECT \* FROM tblSectionLineItemTemplate WHERE TickerID=@TickerID AND SectionID IN (SELECT SectionID FROM tblSectionTemplate WHERE TickerID=@TickerID AND Section='Model Output' AND Action<>'D') AND LineItemID IN (SELECT LineItemId FROM TblLineItemTemplate WHERE TickerID=@TickerID AND LineItem IN ( SELECT LineItem FROM #Tmpdata WHERE ID=@Start ))) BEGIN SELECT @MaxOrder=MAX(ISNULL(OrderID,0))+1 FROM tblSectionLineItemTemplate WHERE TickerI
-
C# EPPlus How to hide range of columnsI am working with EPPlus which generate excel file. now i have to hide range of columns. this code i used to hide range of columns in one go.
var rangecol = ws.Cells["M1:P1"];
var hiddenColumns = rangecol
.Select(cell => cell.Start.Column)
.Distinct()
.Select(rangecol.Worksheet.Column)
.ToList();foreach (var column in hiddenColumns)
{
column.Hidden = true;
}the above code is working and hiding columns but if there are 4 columns in range then it is hiding 4 columns individually not hide in one block. i want 4 columns should be hide in one block instead of 4 blocks. please tell me what mistake is there in my code for which groups of columns are not getting hidden in one block. Thanks
-
AngularJS: ng-repeat not printing data coming from asp.net mvc actionHi i am learning angularjs.i am using AngularJs version v1.8.2 and VS2013 IDE. i am trying to call asp.net mvc action from angularjs controller and print data in page by ng-repeater. ng-repeater not printing any data. This is my asp.net mvc action
public ActionResult GetData(string p1)
{
List crs = new List();
crs.Add(new course { Name = "C#" });
crs.Add(new course { Name = "VB.Net" });
crs.Add(new course { Name = "SQL" });
crs.Add(new course { Name = "RDBMS" });
return Json(crs, JsonRequestBehavior.AllowGet);
}This is my angularjs controller from where i am calling asp.net mvc action.
var myApp = angular.module("MyApp", []);
myApp.controller('myController', function ($scope, $http) {
$scope.Update = function (p1) {
$http({
url: '/Home/GetData?p1='+p1,
method: 'GET'
})
.then(function (response) {
console.log(response.data);
//alert(response.data.Data)
$scope.Courses = response.data;
});
};
});This way i am printing data by ng-repeater
Input :
{{Courses}}
List of Courses
* {{course.Name}}
{{Courses}}
This is showing data i am getting from action. console.log() also showing data. please suggest me which area i need to fix in my code as a result ng-repater should work. Thanks
-
AngularJS $http service not able to call asp.net mvc actionI am learning angularjs. i am using VS2013 and asp.net MVC 5. when user click a link then i am trying to call asp.net mvc action which return json but developer tool showing error called **Failed to load resource: the server responded with a status of 404 (Not Found) Home/GetCourses:1** this is my ASP.Net MVC action
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}public ActionResult Students() { return View(); } \[Route("Home/GetCourses")\] public JsonResult GetCourses() { //ViewBag.Message = "Your contact page."; string\[\] Courses = { "C#", "VB.Net", "SQL", "RDBMS" }; return new JsonResult { Data = Courses, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; } }
This is my routing script of angularjs and $http call.
var app = angular.module("DemoApp", \["ngRoute"\]) .config(function ($routeProvider, $locationProvider) { $routeProvider .when('/', { // This is for reditect to another route redirectTo: function () { return '/home'; } }) .when("/home", { templateUrl: "Template/Home.html", controller: "homeController" }) .when("/course", { templateUrl: "Template/Course.html", controller: "courseController" }) .when("/students", { templateUrl: "Template/Students.html", controller: "studentController" }) //$locationProvider.html5Mode(false).hashPrefix('!'); // This is for Hashbang Mode $locationProvider.html5Mode(true) }) .controller("homeController", function($scope) { $scope.Message = "Home Page!!"; $scope.Title = "Home"; }) .controller("courseController", functi
-
C# How to use place holder in string variableI am doing this way and it works fine.
public static class StringHelpers
{
public static string BuildFormula(this string formulatemplate, string value1, string value2)
{
return string.Format(formulatemplate, value1, value2);
}public static string BuildFormula(this string formulatemplate, string value1, string value2, string value3) { return string.Format(formulatemplate, value1, value2, value3); } }
Calling this way ---------------------
BrokerCountFormula = FormulaTemplate.BrokerCount.BuildFormula(
(StartPeriod + row.ToString()), (EndPeriod + row.ToString())); -
C# How to use place holder in string variableI am doing this way and it works fine.
public static class StringHelpers
{
public static string BuildFormula(this string formulatemplate, string value1, string value2)
{
return string.Format(formulatemplate, value1, value2);
}public static string BuildFormula(this string formulatemplate, string value1, string value2, string value3) { return string.Format(formulatemplate, value1, value2, value3); } }
Calling this way ---------------------
BrokerCountFormula = FormulaTemplate.BrokerCount.BuildFormula(
(StartPeriod + row.ToString()), (EndPeriod + row.ToString())); -
C# How to use place holder in string variablestring interpolation not available in my .net version. i am using c# v5.0 & VS2013.
-
C# How to use place holder in string variableI got fix for my above code. here it is.
private void button1_Click(object sender, EventArgs e)
{
string strBMFormula = Replacement("A10", "Z210");
}private string Replacement(string value1, string value2)
{
return string.Format(@"IF(AND(ISNUMBER({0}),{1}>0,NOT(ISERROR({0}/{1}))),{0}/{1}-1,"""")",value1,value2);
} -
C# How to use place holder in string variablesee the code how i am creating place holder now. _Yoy has a formula used in excel.
private string _Yoy = @"IF(AND(ISNUMBER(C#),P#>0,NOT(ISERROR(C#/P#))),C#/P#-1,"""")";
public string YoY
{
get { return _Yoy; }
set { _Yoy = value; }
}private void button1\_Click(object sender, EventArgs e) { string strBMFormula = YoY.Replace("P#", "2005.13").Replace("C#", "7777.10"); }
I am replacing P# & C# with some value at runtime and program working as expected but i am doing this in large loop where Replace() function is getting called repeatedly which may increase memory use.
@"IF(AND(ISNUMBER(C#),P#>0,NOT(ISERROR(C#/P#))),C#/P#-1,"""")";
here i gave 4 double quote because there would two double quote in excel function. i am using .Net version 4.5 so please suggest me how to create a place holder in string variable and put my value there without using Replace function. i try this approach too but still no luck.
private void button1_Click(object sender, EventArgs e)
{
string strBMFormula = Replacement("A10", "Z210");
}private string Replacement(string value1, string value2)
{
return @"IF(AND(ISNUMBER({value1}),{value2}>0,NOT(ISERROR({value1}/{value2}))),{value1}/{value2}-1,"""")";
} -
C# regarding running multiple taskState1 & state2 will run parallel or State1 will run first and later State2 will run ? please guide me. thanks
var stage1 = Task.Run(() =>
{}); var stage2 = Task.Run(() => { }); // Block until both tasks have completed. // This makes this method prone to deadlocking. // Consider using 'await Task.WhenAll' instead. Task.WaitAll(stage1, stage2);
-
C# reading multiple files by multiple thread issueHere is two approaches to read multiple files by a multiple threads but getting problem. please tell me what is the problem in the below code
for (int i = 0; i < counter; i++)
{
var thread = new Thread(() => GenerateVirusFile(i));
thread.Start();
}please see the full code and tell me what is wrong there.
class Program
{
static string folderPath;
static readonly string fileContent = @"X5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*";static void Main(string\[\] args) { folderPath = "F:\\VirusScan"; int counter = 1000; for (int i = 0; i < counter; i++) { var thread = new Thread(() => GenerateVirusFile(i)); thread.Start(); } Console.ReadKey(); } static void GenerateVirusFile(int i) { string filePath = $@"{folderPath}\\TestForVirusScan\_{i}\_{DateTime.Now.ToString("yyyyMMddHHmmssffff")}.txt"; try { using (StreamWriter writer = new StreamWriter(filePath)) { writer.WriteLine(fileContent); } var timer = Stopwatch.StartNew(); while (true) { if (!File.Exists(filePath)) { Console.WriteLine($"{i}: File was removed in {timer.ElapsedMilliseconds}ms"); break; } else { Thread.Sleep(1); } } } catch (Exception ex) { Console.WriteLine($"{i}: Exception {ex.GetType().Name} occurred: {ex.Message}"); } } }
doing same job Using task
class Program
{
static string folderPath;
static readonly string fileContent = @"X5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*";static void Main(string\[\] args) { folderPath = "F:\\VirusScan"; int counter = 1000; List tasks = new List(); for (int i = 1; i <= counter; i++) { Task