I have this code in my page:
protected void btn_add_Click(object sender, EventArgs e)
{
Session["truck_id"] = truck_id;
Session["user_id"] = user_id;
Session["usertype"] = usertype;
if (usertype == "viewer")
{
Response.Write("Sorry, you do not have access to this page.");
Response.StatusCode = 401;
Response.End();
}
Response.Redirect("JobOrderForm.aspx");
}
I have logged in as viewer and the error message is this
How can I change it to Unauthorized Access?
Change this:
Response.Redirect("JobOrderForm.aspx");
To this:
Response.Redirect("/JobOrderForm.aspx");
/ refers to the root directory. This may help because probably this page and redirected page is not in the same folder.
You have an error on your page. Have you tried debugging it? Set a breakpoint on the first line in the btn_add_Click method and step through to see which line is causing the error.
Related
I created an asp.net site for downloading documents. I handle this with Page.Response.
try {
...
EndpointAddress endPoint = new EndpointAddress("xxxxx.svc");
FileServiceClient fileServiceProxy = new FileServiceClient(binding, endPoint);
// WCF WebService call
Stream stream = fileServiceProxy.GetFileStream(filePath);
Page.Response.ContentType = "application/pdf";
Page.Response.AddHeader("Content-Disposition",string.Format ("attachment; fileName=\"{0}\"", Path.GetFileName(filePath)));
Page.Response.AddHeader("Accept-Ranges", "bytes");
if (buffer != null){
Page.Response.BinaryWrite(buffer);
}
Page.Response.Flush();
}
catch (Exception e)
{
Page.Response.Clear();
Page.Response.ClearContent();
Page.Response.ClearHeaders();
}
finally
{
Page.Response.End();
}
And while the file is loading from a webservice I want to display a hourglass cursor. Showing loading cursor is working.
protected void Page_Load(object sender, EventArgs e)
{
btnDownload.Attributes.Add("onclick", "document.body.style.cursor = 'wait';");
}
But I can't change it back to normal cursor. I think because I don't fire a post back or don't reload the site.
What can I do to set default cursor if buttonClick event is over without site reload!?
Update: Updated the code with the wcf webservice call. I call the webservice with file path and get a stream back which I write to Page.Response.BinaryWriter
# Frédéric Hamidi THX for the link. I change my approach and display a jquery waiting dialog until file transfer is finished.
File download dialog
I want to know-from what url user come from.
So, i use
Uri MyUrl = Request.UrlReferrer;
But when i get only null value from MyUrl:
I have two projects-first is my aspx page, second- redirects to this first project-page with GET parameters.
But when second project redirect to first project- i have :
Object reference not set to an instance of an object.
My second test project so simple:
protected void Page_Load(object sender, EventArgs e)
{
Response.Redirect("http://localhost:54287/go.aspx?id=DEFAULT");
}
First and main project:
protected void Page_Load(object sender, EventArgs e)
{
//Request.ServerVariables('http_referer');
// Request.ServerVariables;
string id = Request.QueryString["id"];
if (id != null)
{
Uri MyUrl = Request.UrlReferrer;
Console.WriteLine(MyUrl);
Response.Write("Referrer URL : " + MyUrl.AbsolutePath);
}
}
Error in :Response.Write("Referrer URL : " + MyUrl.AbsolutePath);
OK, there a a few errors:
Your code:
Uri MyUrl = Request.UrlReferrer;
Console.WriteLine(MyUrl);
Response.Write("Referrer URL : " + MyUrl.AbsolutePath);
In the code above you get a NullReferenceException because MyUrl is null.
The UrlReferer may be null, so you have to check this like:
Uri MyUrl = Request.UrlReferrer;
Console.WriteLine(MyUrl);
if (MyUrl != null)
Response.Write("Referrer URL : " + MyUrl.AbsolutePath);
Also you can never make sure that the UrlReferer can have a value, if the user comes from another website you don't know if this website will provide this value, so you have first to assume the referrer is null (in summary never trust it).
Second, when you use Response.Redirect on your code ran server-side you don't know what is the referrer.
I find this question and this question that will help you to better understand.
UrlReferrer is based off the HTTP_REFERER header that a browser should send. But, as with all things left up to the client, it's variable.
I know some "security" suites (like Norton's Internet Security) will strip that header, in the belief that it aids tracking user behavior. Also, I'm sure there's some Firefox extensions to do the same thing.
Bottom line is that you shouldn't trust it. Just append the url to the GET string and redirect based off that.
Reference:
Stackover flow reference
i have a website "A" in which i am login and redirecting to page "A1" there one text box is asking entry code after filling that code there is a btn GO when i press that btn its redirecting to page "A2" based on that entry code all text filed gets fill. in that page "A2" I have a btn "SAVE & GO to website B"
now wht i want to Based on that entry code i want to redirect to "website B" in new browser on save and go to website B btn.
i am using the code
protected void btnSaveCase_Click(object sender, EventArgs e)
{
Session.Abandon();
Response.Redirect(ConfigurationManager.AppSettings["website B"] + "/Content/CaseProps.aspx?CaseId=" + geturl(CaseId.ToString()));
//Response.Redirect(ConfigurationManager.AppSettings["RCMS"], true);
}
but its not working...
can i use some other code??
anyone please help me...
Can you try this:
Response.Redirect("URL", false);
Response.Redirect(ConfigurationManager.AppSettings["website B"] + "/Content/CaseProps.aspx?CaseId=" + geturl(CaseId.ToString()), false);
By setting it to false, it will terminate your current request.
If the error is that the redirect does not take you to website B then its most probably because you are storing the website b in AppSettings incorrectly. Please store the website B with http:// prefix like this.
<add key="website B" value="http://www.websiteb.com"/>
Ok. So you want to open a new window rather than redirecting. Try this then.
protected void btnSaveCase_Click(object sender, EventArgs e)
{
try
{
Session.Abandon();
string features = "menubar=yes,location=yes,resizable=yes,scrollbars=yes,status=yes";
string name = "mywindow";
string url = String.Format("{0}/Content/CaseProps.aspx?CaseId={1}",
ConfigurationManager.AppSettings["website B"],
geturl(CaseId.ToString()));
string script = String.Format(#"window.open('{0}','{1}','{2}');",
url,
name,
features);
ClientScript.RegisterStartupScript(typeof(Page), "key", script, true);
}
catch (System.Threading.ThreadAbortException)
{
throw;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
On an unrelated side note, its a good practice to use WebsiteB instead of website B in AppSettings
I have restricted access to a site by using Integrated Windows Authentication and turning off anonymous access. This way I can then show them their real name (from looking up on Active Directory and using the server variable LOGON_USER) and do other related Active Directory tasks.
How can I then prompt again for their user credentials, through a 'sign in as other user' link , showing the browser prompt (like you would get on a browser like Chrome or Firefox, or if the site was not in the 'Intranet' zone in IE) rather than a Web Form?
Since SharePoint offers this functionality, I assume there is a way to do this through code, but I don't know what code can do this (using C#). I can send a 401 header which makes the prompt appear, but how do you then confirm if they are logged in?
Maybe this can help you out.
ASP .NET – C# – How to “Sign in as Different User” like in Microsoft SharePoint with Windows Authentication
Try this approach. It is based on disassembled code of the method Microsoft.SharePoint.ApplicationPages.AccessDeniedPage.LogInAsAnotherUser()
First of all, I'm accessing the AccessDeniedPage page using javascript because Sharepoint does something similar:
function GoToSignAs() {
window.location.replace("./SignAs.aspx?signAs=true&returnUrl=" + window.location.toString());
}
<a onclick="GoToSignAs(); return false;" href="javascript:;">SignAs</a>
Then, in your page AccessDeniedPage you use this:
public partial class SignAs : Page
{
private const string LoginAttempts = "LoginAttempts";
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
HttpContext current = HttpContext.Current;
if (current == null)
{
throw new InvalidOperationException();
}
if (GetUrlParameter<bool>("signAs"))
{
HandleSignAs(current, GetUrlParameter<string>("returnUrl"));
}
}
// ...
private static void HandleSignAs(HttpContext context, string returnUrl)
{
int attempts = 0;
HttpCookie attemptsCookie = context.Request.Cookies[LoginAttempts];
if (attemptsCookie == null || string.IsNullOrEmpty(attemptsCookie.Value))
{
attemptsCookie = new HttpCookie(LoginAttempts);
}
else
{
attempts = int.Parse(attemptsCookie.Value, CultureInfo.InvariantCulture);
}
if (!string.IsNullOrEmpty(context.Request.Headers["Authorization"]))
{
// Attempts are counted only if an authorization token is informed.
attempts++;
}
if (attempts>1)
{
attemptsCookie.Value = string.Empty;
context.Response.Cookies.Add(attemptsCookie);
context.Response.Redirect(returnUrl, true);
}
else
{
attemptsCookie.Value = attempts.ToString(CultureInfo.InvariantCulture);
context.Response.Cookies.Add(attemptsCookie);
SendEndResponse(context, 401, "401 Unauthorized");
}
}
private static void SendEndResponse(HttpContext context, int code, string description)
{
HttpResponse response = context.Response;
context.Items["ResponseEnded"] = true;
context.ClearError();
response.StatusCode = code;
response.Clear();
response.StatusDescription = description;
response.AppendHeader("Connection", "close");
response.AddHeader("WWW-Authenticate", "Negotiate");
response.AddHeader("WWW-Authenticate", "NTLM");
response.End();
}
}
FIX: you must use the IIS to work properly
Could somebody please help me?
We are developing a asp.net application using asp.net 2.0 framework. The issue is sporadic. As soon as a particular user hits the site in production a custom error page is shown. I been told that this user could get in successfully some times and after some idle time he is getting this error page. We not even not yet log in to site. Just as soon as i hit the site Ex:- www.Mywebsite.com the custom error is dispalyed. Could somebody help me on this. One more thing i have on my local machine .net 3.5 service pack1 installed and in production on only once server the service pack is installed. Could this be the cause of the problem?. some times it is showing the page and some users custom error. They not even visited the login screen yet. As soon as some users hit the site they see the customer error page, instead of login page. As i told this is happening as the user hitting the site I started checking my load code of index.aspx (page set up in virtual directories documents as start up page) and this is the code i am using.
My each .aspx page is inheriting the PageBase class which has the below method overriden and with the below code. If you see carefully the expiration of "langCookie" been given as 30 minutes. Will this be a problem? Below is a little code of my PageBase and my index.aspx. I am not sure what user's are doing. I heard it comes sporadically, so became hard to reproduce. One more thing since this is mix of asp and aspx pages i used below in web.config, Otherwise i am gettinig the sqaure characters in classic asp pages when i open them.
PageBase.cs Code:-
protected override void InitializeCulture()
{
base.InitializeCulture();
HttpCookie langCookie = null;
if (null == Request.Cookies[SESSION_KEY_LANGUAGE])
{
foreach (string s in Request.Cookies)
{
if (HttpUtility.UrlDecode(Request.Cookies[s].Name) == SESSION_KEY_LANGUAGE)
{
langCookie = new HttpCookie(SESSION_KEY_LANGUAGE);
langCookie.Value = HttpUtility.UrlDecode(Request.Cookies[s].Value); langCookie.Expires = DateTime.Now.AddMinutes(30.0);
Response.Cookies.Add(langCookie);
break;
}
}
}
else
{
langCookie = Request.Cookies[SESSION_KEY_LANGUAGE];
}
if (null != langCookie)
{
if (langCookie.Value != "")
{
CultureInfo cultureInfo = new CultureInfo(langCookie.Value);
ApplyNewLanguage(cultureInfo);
}
}
}
index.aspx.cs:- The starting page in virtual is set as index.aspx
protected void Page_Load(object sender, EventArgs e)
{
//Set sign button as default button for login (press enter)
Page.Form.DefaultButton = "ButtonSignIn";
//Get Cookie Language
if (null == Request.Cookies[SESSION_KEY_LANGUAGE])
{
cookie = new HttpCookie(SESSION_KEY_LANGUAGE);
}
else
{
cookie = Request.Cookies[SESSION_KEY_LANGUAGE];
}
if (null == Request.Cookies[SESSION_KEY_LANGUAGE_FORASP])
{
cookieASP = new HttpCookie(SESSION_KEY_LANGUAGE_FORASP);
}
else
{
cookieASP = Request.Cookies[SESSION_KEY_LANGUAGE_FORASP];
}
if (!IsPostBack)
{
//check if chkbtaccess cookies exists
if (null != Request.Cookies[CHECKACCESS])
{
HttpCookie cookieCheckAccess = Request.Cookies[CHECKACCESS];
string strCKBTC = DecryptUsernamePass(cookieCheckAccess.Value.ToString());
if (String.Compare(strCKBTC, string.Empty) != 0)
{
string[] aryCKBTC = strCKBTC.Split(Convert.ToChar(","));
TextBoxUsername.Text = aryCKBTC[0];
TextBoxPassword.Text = aryCKBTC[1];
CheckBoxRememberMe.Checked = true;
}
}
private string DecryptUsernamePassword(string strText)
{
string strDecryptedUsernamePassword = string.Empty;
strDecryptedUsernamePassword = CommonUtil.EncryptDecryptHelper.Decrypt(HttpUtility.UrlDecode(strText, Encoding.Default));
//strDecryptedUsernamePassword = CommonUtil.EncryptDecryptHelper.Decrypt(HttpUtility.UrlDecode(strText, Encoding.Unicode));
return strDecryptedUsernamePassword;
}
private string EncryptUsernamePassword(string strText)
{
string strEncryptedUsernamePassword = string.Empty;
strEncryptedUsernamePassword = HttpUtility.UrlEncode(CommonUtil.EncryptDecryptHelper.Encrypt(strText), Encoding.Default);
//strEncryptedUsernamePassword = HttpUtility.UrlEncode(CommonUtil.EncryptDecryptHelper.Encrypt(strText), Encoding.Unicode);
return strEncryptedUsernamePassword;
}
As a starting point, you should add some logging and exception handling in this code so that you can narrow down what the error could be. It would also make your code more robust and tolerant to invalid cookie values.
An easy way to do this would be to implement the error handler in Global.asax:
protected void Application_Error(Object sender, EventArgs e)
{
Exception exception = Server.GetLastError();
}
This should give you the exception that occurred, which you can then examine (eg. in the debugger, log it to a file, etc...) to see what is causing the error.
For a temporary measure, you could turn off custom errors in web.config:
<customErrors mode="Off"/>
This will enable you to see the exception in your web browser when it occurs. I wouldn't recommend that you use that setting on a live site though.