Access to url from within an mvc project - asp.net

Is it possible to configure the route within a asp.net mvc project when redirecting to an external url?
for example
public ActionResult MyUrl()
{
return Redirect("http://www.myurl.com/");
}
I dont want the the url of http://www.myurl.com/ to be displayed in the address bar but
MyProject/MyUrl
I tried this
routes.MapRoute(null, "MyUrl", new { controller = "Home", action = "MyUrl" });

For external URL you could not use Server.TransferRequest. This method just works for same site. Use iframe to your view instead:
public ActionResult MyUrl()
{
return View();
}
In your view use iframe with external URL:
<body>
<iframe src="http://www.myurl.com/"></iframe>
</body>
By using this method user see MyProject/MyUrl in the address bar. But keep in mind user could easily discover actual URL by viewing source of HTML file.

Related

Why won't CSS won't work on specific situation

So I'm working a project of a Website. In it, there's an admin page where I can add or remove images that will be shown on the website. I created a Controller for the Main Admin page alone, and then I created a controller for every type of information that can be changed through that page (Porfolio, banner, etc). All the pages are styled by CSS. So when my AdmController returns the view with the main Admin page, everything works fine
The adress for the main Admin Page results in localhost:8000/adm
But once I try to open a view where I would add an image to be shown on the Main page, CSS simply won't work. To acess, say, the add banner page, I have a BannerController that will return a "form-banner" view, resulting in the adress localhost:8000/adm/banner. In this page CSS does not work.
I wanted to test further so I created a new Route that would take me directly to the create banner page without going through the admin page, and also not using any Controllers at all. I got the adress localhost:8000/banner. Now CSS works.
Any ideas why?
These are the routes including the one I created just to test the view:
Route::resource('adm', 'AdmController');
Route::resource('adm/banner', 'BannerController');
Route::get('banner', function () {
return view('admin/form-banner');
});
This is the AdmController:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class AdmController extends Controller
{
public function index()
{
return view('admin/index');
}
}
This is how the BannerController is returning the mal-functioning View:
public function create()
{
return view('admin/form-banner')
And this is the point in the Main Adm View (the one that works) where It calls the BannerController:
<ul class="nav-second-level" aria-expanded="false">
<li>Create new banner</li>
Add your CSS like below
<link href="{{ asset('css/app.css') }}" rel="stylesheet">
the absolute path after your public folder

Json get not working through azure but working locally

I have created a asp.net webapi and hosted it through azure.
This works fine when I run host/api/carparks. It also works when I run an ODATA query string
host/api/carparks?$Filter%20eq%20%27Liverpool%27
Google chrome returns the results as JSON as I want them.
The problem I am having is, I need to create a "Client" application to visualize my data. I have created a really simple for loop to return my data for testing purposes, once I have data returned I can start creating my application.
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript">
function getStations() {
var town = document.getElementById("town").value;
var stationList = "<p>";
var uri = "http://localhost:38852/api/carparks?$filter=Town%20eq%20%27" + town + "%27";
$.getJSON(uri,
function (data) {
$('#here_data').empty(); // Clear existing text.
// Loop through the list of products.
$.each(data, function (key, val) {
stationList += val.Name + '<br />';
});
stationList += "</p>";
document.getElementById("here_data").innerHTML = stationList;
});
}
$(document).ready(getStations);
</script>
</head>
<body onload="getStations()">
<h1>Stations API</h1>
<p>Enter town</p>
<input type="text" id="town" value="Derby" />
<input type="button" value="Find Stations" onclick="getStations()" />
<div id="here_data">
<p>Car parks go here</p>
</div>
</body>
</html>
My client app works perfectly when I run my web api locally but when I change the getJSON request URI to my azure one (Which works in the browser!) nothing happens.
I have tried uploading my client app to azure and testing it that way but nothing :(
Is there any Azure settings that need to be changed?
Looks very much like a cross-origin issue.
The issue does not occur when you call the Service directly in your browser but only when you issue an Ajax call from a different domain (localhost vs. *.azurewebsites.net).
If you want to access your Web Api service with an Ajax call from a different domain you need to enable Cross Origin Resource Sharing (CORS).
A detailed article is found here:
http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api
Quoted from the link:
Install-Package Microsoft.AspNet.WebApi.Cors
Open the file App_Start/WebApiConfig.cs. Add the following code to the
WebApiConfig.Register method.
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// New code
config.EnableCors();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
Next, add the [EnableCors] attribute to the TestController class:
using System.Net.Http; using System.Web.Http; using
System.Web.Http.Cors;
namespace WebService.Controllers
{
[EnableCors(origins: "http://mywebclient.azurewebsites.net", headers: "*", methods: "*")]
public class TestController : ApiController
{
// Controller methods not shown...
}
}
For the origins parameter, use the URI where you deployed the
WebClient application. This allows cross-origin requests from
WebClient, while still disallowing all other cross-domain requests.
Later, I’ll describe the parameters for [EnableCors] in more detail.
Do not include a forward slash at the end of the origins URL.
Thanks to #viperguynaz and #florian I have fixed my issue. I changed the CORS option in Azure portal. (When I first did it I didn't remove the forward slash at the end of the URL). I removed the slash and it works.
I have also used the info given by #florian to help me understand CORS more.
Thanks again
1 happy joe :)

ASP.NET MVC 5 URL Depend on Selection

I have a page created on VS13 MVC 5 based on ASP.NET, on my navigator I have my dropdown menu
While I click on Phones link I have URL as: www.sitename.com/phones and it will list all phones which I have on my data base, while I choose a brand (e.g: Samsung) I want my URL will be www.sitename.com/phones/samsung
Simple question I don't want create a view for each brand or model of phone because there are a lot, I can just use SQL and list them on the same page but how to change my URL depending on my choice ? Is the only way is Attribute Routing?
Appreciate any suggestion.
If you are using JS/jQuery you can use the History.js api. https://github.com/browserstate/history.js/
You can then use History.pushState(insert parameters here);. This will not only change the url to your choice but also allow users to go back and forward like usual, it also keeps SEO with web crawlers I think.
You can add a Route to your route config
in RouteConfig.cs
routes.MapRoute(
name: "Product",
url: "{controller}/{productCategory}/{productName}",
defaults: new { controller = "Product", action = "Index", productCategory = UrlParameter.Optional, productName = UrlParameter.Optional }
);
in product controller
public ActionResult index(string productCategory,string productName)
{
//return items by productCategory/ProductName
}

Ignore embedded resources routing ASP.NET 4 WebForms

I am using routing in asp.net 4 webforms. I have a theme dll which contains all the images, css and js files required for look and feel. I have only 1 page which dynamically loads the control in the page. I use routing to distinguish the request. Following routes are defined:
routes.Ignore("{resource}.axd/{*pathInfo}");
routes.MapPageRoute("Default-All-Pages", "Pages/{*OtherParams}", "~/Default.aspx", false);
Handler for managing the embedded resources is already defined. When the application is executed it by virtue of code, redirects the request to default.aspx. it then goes ahead to load the css file and again routes the request to default.aspx.
I want it to route the css/jpg request to virtual path handler and not the page. What route should I define so that the request for files will not be handled by default.aspx page?
routes.Ignore("{*allaspx}", new { allaspx = #".*\.aspx(/.*)?" });
routes.Ignore("{*allcss}", new { allcss = #".*\.css(/.*)?" });
routes.Ignore("{*alljpg}", new { alljpg = #".*\.jpg(/.*)?" });
routes.Ignore("{*alljs}", new { alljs = #".*\.js(/.*)?" });
This solved my problem.
The same way you're ignoring HttpHandlers, you can add ignore rules for css and jpg files:
routes.Ignore("{resource}.css/{*pathInfo}");
routes.Ignore("{resource}.jpg/{*pathInfo}");
These will be excluded from the route table and will be handled by any registered handlers/modules/ISAPI filters.

Returning to Calling Page Within an Area Using UrlReferrer

I have created a new MVC2 project using the ASP.NET MVC2 Web Application, which gives me the default web site. I have added a simple area in which I had a Home Controller and an Index view. That cuased the first problem with the compiler giving "Multiple types were found that match the Controller name 'Home'". I changed Home to Main and it compiled.
I added a new tab to reference the Index view in my area, opened the website and started clicking the tabs. When I visited the Area index page, I couldn't go back to the Home or About page without changing the menu, as follows:
<ul id="menu">
<li><%= Html.ActionLink("SampleArea.Main", "Index", "Main", new { area = "SampleArea" }, null)%></li>
<li><%= Html.ActionLink("Home", "Index", "Home", new { area = "" }, null)%></li>
<li><%= Html.ActionLink("About", "About", "Home", new { area = "" }, null)%></li>
</ul>
I could then cycle through the tabs correctly. I then changed the code in the LogOff view in the Account controller, as follows:
public ActionResult LogOff()
{
FormsService.SignOut();
//return RedirectToAction("Index", "Home");
return RedirectToAction(Request.UrlReferrer.AbsolutePath.ToString());
}
I am using UrlReferrer.AbsolutePath to return to the calling page if the User logs off. If the calling page happens to be the View in SampleArea, .AbsolutePath contains "/SampleArea". This is because the controller and view are the defaults, and so they are not included. As it continues, I get the following error message:
The resource cannot be found.
Description: HTTP 404. The resource
you are looking for (or one of its
dependencies) could have been removed,
had its name changed, or is
temporarily unavailable. Please
review the following URL and make sure
that it is spelled correctly.
Requested URL: /Account/SampleArea
My understanding is that /Account has been added because that is the controller it was in when LogOff was executed. It thinks /SampleArea is an action and therefore added the current controller to complete the route.
Using UrlReferrer.AbsolutePath, is there any way I can specify SampleArea as an area, or is there something else I can do to return to the correct page?
New Addition
This is even stranger than I thought. I opened the website I am currently developing and changed the return statement in view LogOut to return using AbsolutePath. A breakpoint reveals it contains "/Club/PrivacyPolicy". However, I get the same error message with the following difference:
Requested URL: /Login/Club/PrivacyPolicy
Why on earth should it prefix it with /Login which is a View, rather than /Account which is a Controller? In fact, why should it prefix it with anything at all? /Club/PrivacyPolicy
is a valid route in Global.asax.cs.
I have finally figured out how to return to the page you were on when you triggered the LogOn or LogOut request. I have used the following piece of code.
Html.ActionLink("Member LogOn", "LogOn", "Account", new { area = "", returnUrl = HttpContext.Current.Request.RawUrl }, null)
This generates
<a href='/LogIn/LogOn?returnUrl=%2FContactUs'>Member LogOn</a>
for example.
In my HttpPost ActionResult LogOn, I then have
if (!String.IsNullOrEmpty(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
Sometimes I find I just need HttpContext.Request.RawUrl.
I'm not quite sure why it has generated /LogIn/LogOn instead of /Account/LogOn, but it works as expected.

Resources