ASP MVC Relative URL Path(not file) - asp.net-mvc

I have a link to <a href='/ViewReport'> on my local host that works fine, but on the server the whole site is in a folder "serverfolder", so the link becomes http://somesite/serverfolder/ViewReport, which isn't a valid url. I have seen how to use ~ to access the root directory for files, but not how to do this with url paths. I want to use the same link for both local and remote deployment. How would I achieve this? Thank you!

Do this:
var urlHelper = new UrlHelper(Request.RequestContext);
string url = Request.Url.GetLeftPart(UriPartial.Authority)
+ urlHelper.Action("ViewReport",
new { userId = UserName, reportId = PI.ElementAt(i).TempUserID });
Or, if you prefer not to use the UrlHelper.Action, you do it like this:
string url = Request.Url.GetLeftPart(UriPartial.Authority) + "/ViewReport...";

Related

Vaadin URL Mapping

Is there a way do not enter a specifc url mapping (vaadin.urlMapping)? But I also want to still use swagger for example (ip:8080/swagger-ui/index.html)? It would be great to exclude some mappings from vaadin.
Thanks for your help!
Best Regards, Thomas
Put the URL/Part of URL/IP in the properties file.
Put the URL/Part of URL/IP in the web.xml file.
In some cases you want the remote URL to be different than the local URL (or remote SSL URL to be different than the local URL).
In that case, I placed both IP and domain on to web.xml in two different contexts.
final String serverUrl = new URL("" + ((VaadinServletRequest)VaadinService.getCurrentRequest())
.getHttpServletRequest().getRequestURL()).getAuthority();
final String serverProtocol =
((VaadinServletRequest)VaadinService.getCurrentRequest()).getHttpServletRequest().getProtocol();
final boolean serverSecure =
((VaadinServletRequest)VaadinService.getCurrentRequest()).getHttpServletRequest().isSecure();
if(!serverSecure){
UI.getCurrent().getSession().setAttribute(
ResourceProperty.configBundle.getString("APPLICATION_URL"),
"http:" + serverUrl);}
else{
UI.getCurrent().getSession().setAttribute(
ResourceProperty.configBundle.getString("APPLICATION_URL"),
"https:" + serverUrl);}

how to pass a folder path to mvc controller

I am trying to pass a folder path to a download controller using #Html.ActionLink, but I am getting could not find the location error like
Could not find file 'C:\Teerth
Content\Project\Colege\WebApp\Media\#item.Content'
However when I give the hard coded value it does work. May I have suggestions what is wrong with that.
Here is my code:
Action method:
public FileResult Download(string fileName, string filePath)
{
byte[] fileBytes = System.IO.File.ReadAllBytes(filePath);
string documentName = fileName;
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, documentName);
}
view
#Html.ActionLink("Download", "Download", "Marketing", routeValues: new
{
fileName = #item.Content,
filePath = Server.MapPath("~/Media/#item.Content"),
area = "AffiliateAdmin"
}, htmlAttributes: null)
Like mentioned in comments, you've got an error in your view:
The code ("~/Media/#item.Content") renders as C:\Teerth Content\Project\Colege\WebApp\Media\#item.Content, where you actually want Server.MapPath("~/Media/" + #item.Content) to find the actual filename.
But you need to reconsider this design, as it opens up your entire machine to the web. Someone is bound to try Download("C:\Teerth Content\Project\Colege\WebApp\web.config", "web.config"), exposing your connection strings and other application settings, not to mention other files on your server you really don't want clients to download.

HttpContext AbsolutePath goes to wrong URL for aliased pages - C#

On my website each page has links that are created in the codebehind, where the links are the current URL with one query parameter changed. To do this, I've been using this method (this specific example is for the pagination):
var queryValues = HttpUtility.ParseQueryString(HttpContext.Current.Request.QueryString.ToString());
queryValues.Set("page", num);
string url = HttpContext.Current.Request.Url.AbsolutePath;
string updatedQueryString = "?" + queryValues.ToString();
string newUrl = url + updatedQueryString;
return newUrl;
This worked on my local version fine. However, when I created each page in Ektron and added a manual alias, the URLs generated still went to the file location in the solution. For example, my original page was /WebAssets/Templates/EventListView.aspx. I created the page in Ektron as /Alumni/Events/List. I can go to /Alumni/Events/List, but then when I click on a page button the page that loads is /WebAssets/Templates/EventListView.aspx?page=2 instead of /Alumni/Events/List/?page=2
I found one solution:
var rawUrl = HttpContext.Current.Request.RawUrl;
var url = rawUrl.Split('?')[0];
string newUrl = url + updatedQueryString;
Use the QuickLink property of the primary contentblock for /Alumni/Events/List, this will be the alias use want to use for your page links or for redirects to the same page. This is probably ContentData.QuickLink if you're already loading the ContentData at some point in the code.
Notes:
Aliasing may remove your "page" querystring parameter by default, to resolve this issue, edit your alias in the Workarea to have a "Query String Action" of "Append".
Make sure you preprend a "/" to the QuickLink value (if it's not absolute and not prepended already) if using it on the frontend, otherwise your links will bring you to something like /Alumni/Events/List/Alumni/Events/List?page=2, which is no good.

Breeze is not working with some project settings

I have a problem using breeze on a project based on John Papa's HotTowel. I configured breeze like:
var mgr = new breeze.EntityManager('breeze/Breeze');
everything is ok but in the case I change the Project properties Start Action from Current Page to Specific Page: HotTowel/Index and breeze doesn't work properly.
I've checked the requests using firebug. It seems in this case application sends a GET request like this:
http://localhost:53180/HotTowel/Index/breeze/Breeze/Metadata
instead of
http://localhost:53180/breeze/Breeze/Metadata
I've also checked this part of breeze.js which is going to send get request.
The url parameter is set to breeze/Breeze/Metadata in both cases which seems correct.
ctor.prototype.fetchMetadata = function (metadataStore, dataService) {
var serviceName = dataService.serviceName;
var url = dataService.makeUrl("Metadata");
var deferred = Q.defer();
var that = this;
ajaxImpl.ajax({
url: url,
dataType: 'json',...
I've also tried ~/breeze/Breeze but it didn't work as remote service name.
As I'm new to web, probably it's not related to breeze.
The question is why the ajax call (or breeze) depends on how the project activates?
Add a / character to your configuration to execute the request relative to the base directory:
var mgr = new breeze.EntityManager('/breeze/Breeze');
The reason why this happens is because you specified a relative path for the EntityManager and if your url is localhost:53180/HotTowel/Index then the relative url for the EntityManager is localhost:53180/HotTowel/Index + /breeze/Breeze.
To correct the issue, change your EntityManager path to the following:
var mgr = new breeze.EntityManager('breeze/Breeze');

Facebook OAuth + AppHarbor workaround on random port

I a have a sample app, hosted on AppHarbor and now want to integrate authorization through facebook. So i downloaded nugget Facebook.Web.Mvc package to implement it.
After reading tutorial, in controller i have method:
public ActionResult Login(string returnUrl)
{
var oauthClient = new FacebookOAuthClient(FacebookApplication.Current) { RedirectUri = GetFacebookRedirectUri() };
if (!string.IsNullOrWhiteSpace(returnUrl))
{
returnUrl = Url.Action("Index", "Facebook");
}
dynamic parameters = new ExpandoObject();
parameters.scope = ExtendedPermissions;
var state = new { csrf_token = CalculateMD5Hash(Guid.NewGuid().ToString()), return_url = returnUrl };
parameters.state = Base64UrlEncode(Encoding.UTF8.GetBytes(JsonSerializer.Current.SerializeObject(state)));
SetFacebookCsrfToken(state.csrf_token);
string s = oauthClient.GetLoginUrl(parameters).AbsoluteUri;
ViewBag.FacebookLoginUrl = s;
//new LogEvent(s).Raise();
return View(new AccountModel());
}
View:
<a href="#ViewBag.FacebookLoginUrl" id="lUrl">
<div class="fblogin"></div>
In localhost this works for me.
But when i upload it to appharbor, i see, that generated link indicates to address + port 16013 (as support told always random port). So clicking it shows me facebook login window, than blank page.
I manually configured my app settings in facebook to this port but it did not helped.
Also i tried to access my site through this port - nothing.
Then i changed port number through jquery to 80, its also did not help.
you have had such problems?
I'm not familiar with the Facebook api, but I've had a similar problem.
I suspect that the returnUrl value being passed in is incorrect. It probably contains a port number that AppHarbor uses internally for load balancing.
See this article on how to create a public url for AppHarbor:
http://support.appharbor.com/kb/getting-started/workaround-for-generating-absolute-urls-without-port-number
Then make sure that the value in your returnUrl is publicly available.
You can now set the aspnet:UseHostHeaderForRequestUrl appSetting to true which effectively solves this problem. This can be done by adding a Configuration Variable to your application with the corresponding key and value.
Source on AppHarbor

Resources