#Url.Action in the View SOMETIMES doesn't work - c#

In my view I have something like the following
<img src="#Url.Action("GetImage", new {param1 = ViewBag.Param1, page = ViewBag.Page })" alt="" />
This works some of the time. However, every now and then the image just doesn't load. I set a breakpoint in the GetImage ActionResult and when the image isn't loading, the breakpoint isn't being hit.
This behavior seems to be completely random, if I just refresh the page over and over sometimes it works sometimes it doesn't. Any ideas or suggestions?

view :
<img src="#Url.Action("GetImage",new {name="google.png"})" alt="" />
and controller action look like below
[AcceptVerbs(HttpVerbs.Get)]
public FileResult GetImage(string name)
{
var path = #"C:\VS2015\Images\" + name;
return new FileStreamResult(new FileStream(path,FileMode.Open),"image/jpeg");
}
Hope your controller action code look like above.
it will work fine.

(Should be a comment but too long...)
Before you start diagnosing server-side issues, find out what the actual problem is.
Open up the browser developer tools (F12 on win), switch to the Network tab and keep refreshing until the problem occurs. (Note: there's a setting to disable the browser cache when dev tools are open, make sure to uncheck it to replicate the situation accurately)
When the problem occurs, scroll down to the request for the image and check if ti was fetched from the server or the local cache. If from the server, there should be a status code which will give you a hint (404/500) and the response body may contain useful information (like a full stack trace if your server is configured to show errors). At the very least, a server response means that a connection was made and that there should be some useful information in server logs.
It's also possible the problem is with either the browser cache or a proxy between the client and server.
Finally, if it is a problem server-side and you can't see error details in the browser, have a rummage through the servers event logs. All .Net errors are recorded there (by default at least).
Once you've got more information on what's causing the problem, edit your question and we can go from there.

Related

Updating the displayed URL in the browser using .NET Core

So, I have a certain webpage (view) that I have created. I have a requirement where I need to update the displayed URL in the browser's to show a different path to this page and update the querystring.
Update: I don't want to actually redirect the page, this is merely a cosmetic update. To make the URL appear differently that what it was. It's a requirement our customer support team wanted. :p
Ex.
https://www.myserver.com/error/
I need to update the path in the URL depending on the type of error, like so:
https://www.myserver.com/#/order-completed?var=someguid
My error page handles various situations you see.
I know this is easily done in JS, but I want to be able to do this from my error page Controller.
Could someone lend a hand? I'd super appreciate it!
I think "update the path" means you simply have to redirect the browser to that url. If you are using ASP.NET MVC, you can use the Redirect controller method like this:
return Redirect("https://www.myserver.com/#/order-completed?var=someguid");
So, I went the way of JS afterall. I call it from window.onload in the View.
var fromController = '#ViewData["NewURL"]';
histoy.pushState(null, '', fromController);
In the Controller, in the Index() action
ViewData["NewURL"] = #"/myURL/myview?user=2342434";
return View();

Internet Explorer redirect on all .Net Core project pages

I'm a .Net Core beginner and look for a solution to protect the application from IE.
I got the following code working in Controller:
string userAgent = Request.Headers["User-Agent"].ToString();
var flagsIE = new [] {"MSIE", "Trident"};
if(flagsIE.Any(userAgent.Contains)){
return RedirectToAction("BadBrowser");
}
Now if someone is trying to visit the page using IE, they get redirected to an info-page asking them to use a modern browser. Instead of adding this code to every single Controller.cs I would like to add it on project level, so that it get's executed independent from the location within of the project.
And, I know that this can be achieved with _Layout.cshtml, my question is:
Where and how would I implement a function to get it executed for all requested views withing the project without adding it every single request within Controller.
Thank you in advance.
As Icepickle suggested, in the comments of my question, I used middleware in Startup.cs and got the desired result:
app.Use(async (context,next) =>
{
string userAgent = context.Request.Headers["User-Agent"].ToString();
var IEkeywords = new [] {"MSIE", "Trident"};
if (IEkeywords.Any(userAgent.Contains)){
context.Response.Redirect("/IE/redirect/badbrowser.html");
return;
}
await next();
});
You can try to add js in _Layout.cshtml to detect the browser is IE:
<script>
var isIE = false || !!document.documentMode;
if (isIE) {
window.location.href = "/Home/ForbidInfo";
}
</script>
Then create a view named ForbidInfo under Home controller which to show the message to user that he cannot use the IE to show views.
(Notes: this view's Layout must be null ,or it will enter an endless loop)
#{
ViewData["Title"] = "ForbidInfo";
Layout = null;
}
<h1>Please use a modern browser!</h1>
After these settings, when you running a view in IE, it will be redirected to the FordidInfo page.
If your page does not use _layout, then you need to add the js on the corresponding view separately to ensure that it will not be displayed in IE.
Never do that. Excluding browsers with redirects, is what lead to massive user agent spoofing. Effectively making that AgentId useless. And the way you wrote it, you may get a lot of false-positives.
It is also a bad idea from the early days of the internet, we are hoping to get rid off:
https://en.wikipedia.org/wiki/User_agent#User_agent_spoofing

Query String Parameter Being Lost on Request

i'm developing an MVC 4 web application.
I'm trying to make an url that changes in an authorized/unauthorized context.
I'm generating the following url for unauthorized user:
http://localhost/vendas-web/Login?ReturnUrl=%2Fvendas-web%2FClienteNovo%2FIndex%299999
The first time I've tested, it worked just fine.
But.. the second time I've tried, the query string got lost.. and the url turned into:
http://localhost/vendas-web/Login
When i test it against chrome on anonymous tab, it works FINE.
When i change the value of the last parameter, it works FINE.
There's some sort of cache related to this ?
What i'm doing wrong ?
Soo, my question is:
How do i keep my full url in any scenario ??
Ty
There's really not enough information here, but what you're likely talking about is that the first time a user needs to be authorized, they are automatically redirected to the first URL, which includes the ReturnUrl bit. That's built into the framework to allow the user to be redirected back to that URL after logging in. However, if you need to persist this past that initial first redirect to the login page, that's on you. Any links must manually add the query string param:
#Url.Action("SomeAction", new { ReturnUrl = Request["ReturnUrl"] })
And any forms must include it as a hidden input:
#Html.Hidden("ReturnUrl", Request["ReturnUrl"])
Otherwise, yes, it will be lost, because the literal URL you're now requesting doesn't include it. It's not just magically appended.
My problem was cache...
I've used this annotation to avoid using cache by application.
[OutputCache(NoStore = true, Duration = 0)]

MVC Redirect to another page

I have a controller which processes an uploaded file.
In that controller, I return the user to a SharePoint list depending on the successful parsing of that file. I am able to enter a direct URL, but I am opening this page in a form so I need to change the window.top.location instead of just window.location. I tried doing this a few ways such as returning a JavaScript result, but I received some browser warning messages I'd like to avoid.
I ended up making a partial razor view which grabs a parameter from the query string in order to determine which list it should go to. The function works fine, but the page is seemingly inactive when I return it using:
return Redirect("~/Parsing/ParsingRedirector?List=MasterDealer");
My page exists in the folder, but I get an error stating "The resource cannot be found. "
Any reason why that's happening? I admittedly don't have a full understanding of MVC or even close to it at this point.
Try this:
return RedirectToAction("ParsingRedirector", "Parsing", new { List = "MasterDealer"});
This may be of help:
http://www.dotnet-tricks.com/Tutorial/mvc/4XDc110313-return-View()-vs-return-RedirectToAction()-vs-return-Redirect()-vs-return-RedirectToRoute().html
Keep in mind that, per that article, in the case of Redirect "you have to specify the full URL to redirect."

Postback Fails On Default Document

So I've created a Web Application (not Web Site) with ASP.NET (C#) and it compiles just fine in the VS13 environment. But when I publish it on IIS, the Postback on the Default Document fails. The Default Document is called LoginPage.aspx. As soon as I click the <asp:Button> to run my code behind, all it does is refresh the page. This project has been published on my local 127.0.0.1 IP address for the time being.
I know this has been a documented issue, but I've tried many solutions and have not come across a resolution. Some solutions I have attempted:
Creating a brand new Web App with minimal code to attempt accessing any Postback with no success.
I tried the first solution presented here with no success: https://stackoverflow.com/a/7367076/4204026
I also tried URL mappings:
<urlMappings>
<add url="~/login" mappedUrl="~/Views/LoginPage.aspx" />
<add url="~/login/" mappedUrl="~/Views/LoginPage.aspx" />
</urlMappings>
I'm honestly at a loss as to what's happening here. One thing I did notice is when the application is being run through Visual Studio, the <form> tag on the LoginPage.aspx appears in Chrome as:
<form method="post" action="LoginPage" id="ct101" class=".myForm">
Through IIS:
<form method="post" action="./" id="ct101" class=".myForm">
Not sure if that's a problem either. I tried hard-coding the action to login to see what would happen and it does redirect to the correct page, but as suspected no Postback was fired - My Session variable returned null and no query string was used.
Here's the related LoginPage.aspx front-end code (trimmed out a bunch of unrelated HTML):
<%# Page Title="DREW KENNEDY | WELCOME" Language="C#" MasterPageFile="Site.Master" AutoEventWireup="true" CodeBehind="LoginPage.aspx.cs" Inherits="MyMedia.Views.LoginPage" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<!-- form is located on Site.Master -->
<asp:Button OnClick="LoginBtn_Click" CssClass="login" runat="server" name="submit" Text="Sign In" />
</asp:Content>
And the LoginBtn_Click method in LoginPage.aspx.cs:
protected void LoginBtn_Click(object sender, EventArgs e) {
//Tried the following line while commenting out everything else to make sure Postback is being ignored
//Response.Write("<script>alert('Test');</script>");
try {
AbstractPersistenceDecorator decorator = new PersistenceDecorator();
string uname = username.Text.Trim();//username is a TextBox Control
string pass = password.Text.Trim();//password is a TextBox control
bool isCookieRequested = CheckBox.Checked;
if (decorator.authenticate(uname, pass)) {//calling SQL Server for authentication
User AuthenticatedUser = (User)Session["User"] ?? decorator.getUserInfo(uname);
if (Session["User"] == null) Session["User"] = AuthenticatedUser;
if (isCookieRequested) {
HttpCookie cookie = new HttpCookie("username", AuthenticatedUser.Username);
cookie.Expires.AddDays(7);
Response.Cookies.Add(cookie);
} else {
Session.Timeout = 15;
}
Thread.Sleep(1600);
//string redirect = string.Format("dashboard?username={0}", AuthenticatedUser.Username);
Response.Redirect("dashboard?username=" + AuthenticatedUser.Username);
}
} catch (Exception ex) {
//who cares?
}
}
Final pieces of info:
Running IIS 8.0
Application created with 4.5 Framework, Application Pool is also 4.5 Framework
I have ensured that ASP.NET is installed on IIS
I do have URL ReWriting in the global.asax file, though I'm not sure if that is related in any way (I don't see how).
I have no Default.aspx page
EDIT:
Just tested the project through 127.0.0.1 on IE11 and FF with the same result.
EDIT #2:
Additional things I have tried with no success:
I tried removing my URL Rewriting
I tried adding an empty URL Rewrite rule, i.e. ("Empty URL", "", "~/Views/LoginPage.aspx")
Additional notes:
I do not use Telerik
I do not use ISAPI
The project in Visual Studio was set to debug and not release
I apologize for not giving enough information in the OP as I have found the answer. It turns out it had nothing to do with ASP.NET, but rather SQL Server. I stripped the code bare and after adding back one piece of code at a time and stripping away all exception handling, I found through IIS that IIS APPPOOL\.NET vX.X did not have permissions to access the database.
What I had to do is:
In MSQLSM, add a new Login for IIS APPPOOL\.NET v4.5
Further on, I found out that it needed the correct permissions to perform certain commands after receiving the following exception:
The SELECT permission was denied on the object 'X', database 'X', schema 'dbo'
This Was Solved Here
Give that new Login the proper access. Login Properties > User Mapping > checking db_datareader and public.
The code behind now executes. It still leaves the question why it was prohibiting any Postbacks, even if I removed any SQL Connectivity in the code behind. Very strange.
Anyway, thanks to those who helped.
I suggest that you redirect from the default page to the Expected page then this should work. Iis default page handling is done through isapi to handle static content so the post data may not survive

Categories