w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
httpcontext current server mappath shows c:inetpubwwwroot when the current location is somewhere else
Use Server.MapPath("~"), which returns the physical path of the root of your application. The Server.MapPath("/") you are using, returns the physical path of the root of the domain.

Categories : Asp Net Mvc

httpcontext.current.server.mappath and unit testing
You need to abstract out the loading of the XML file. Such as; class WebContentLocator : IContentLocator{ public string GetPath(string relativePath) { return HttpContext.Current.Server.MapPath(relativePath); } } class TestContentLocator : IContentLocator{ string _contentRoot; public TestContentLocator() { _contentRoot = ConfigurationManager.AppSettings["ContentRoot"]; } public string GetPath(string relativePath) { return Path.Combine(_contentRoot, relativePath.Replace("~", string.empty); } } interface IContentLocator { string GetPath(string relativePath); } and in your test inject the TestContentLocator into the code that is doing the XML loading, which would by default be using the WebContentLocator. Fds.ReadXml(_content

Categories : Asp Net Mvc

500 internal server error on asp.net page caused probably by server.MapPath
The problem is you're trying to save to the App_Data folder - this folder is only available to actual code. You cannot write to it by default, you also cannot output its contents to your website. The App_Data is specifically meant for Data only - such as XML & Database files - see here for more info: MSDN App_Data folder So, even if you managed to save a file into app_data you would not be able to display it - you would receive an unauthorized access error message. To fix, change this: HttpContext.Current.Server.MapPath("~/App_Data/setP") to something like this HttpContext.Current.Server.MapPath("~/uploadImages/setP") Essentially give yourself a different folder to upload to. Update Following from the comments it seems you are getting the A Generic error occurred in GDI+...

Categories : Asp Net

Difference between WebOperationContext.current and HttpContext.Current
WebOperationContext is typically used in a WCF REST method so that method can access the incoming request and outgoing response. HttpContext is typically used in an ASP.NET WebForms page or web method for ASMX Web Service, when incoming request and outgoing response can be accessed. They are designed for different project types (WCF REST/ASP.NET WebForms) so you should not use them in a wrong project type. About when the value of .Current is null, that's even more complicated. Even if you are calling this property in the correct project type, you need to make sure the call is made on a proper thread. Only on the thread that handles the request (which also sends out the response) you can access the current context. On any other threads (background threads, or new threads created by you)

Categories : C#

ASP.net file upload from a non server - issue with Server.MapPath?
You wrongly getting file name. You should use below code string filename = Path.GetFileName(FileUploadControl.FileName); Of course change control name to your own. Please See: http://msdn.microsoft.com/en-us/library/aa479405.aspx

Categories : Asp Net

Server.MapPath() with IIS URL Rewrite Module 2.0
I was looking for the same thing so I gave it a try in a test app. It appears that Server.MapPath() does not acknowledge URL Rewrite Module rules. Here is how I tested using an empty web project (Razor syntax): Rewrite rule: <system.webServer> <rewrite> <rules> <rule name="Rewrite rule1 for test1"> <match url="^test1(.*)" /> <action type="Rewrite" url="{R:1}" appendQueryString="true" /> </rule> </rules> </rewrite> </system.webServer> cshtml: <p> The URL for this page is @Request.Url.AbsoluteUri . <br /> MapPath of /test1 is @Server.MapPath("~/test1") <br /> MapPath of / is @Server.MapPath("~/") </p> I

Categories : Iis

Using Server.MapPath() to generate img src, not working
APP_Data is a restricted folder intended for Datasources such as Database only. ASP.Net will not deliver a file in here - try it by going to the URL for that image directly (I.E www.mysite/App_Data/5/62.jpg ) and you will see the error message HTTP Error 403 - Forbidden. Put your images in a folder outside of this and you will be fine, such as a folder in the root Called Images

Categories : Asp Net

Using Server.MapPath to save a file
You can access it through the current context HttpContext.Current.Server.MapPath("~/App_Data/stored"); to get the full file path : var filePath = Path.Combine(HttpContext.Current.Server.MapPath("~/App_Data/stored"), package.Id + ".zip");

Categories : Asp Net

MultipartFormDataStreamProvider vs HttpContext.Current
This is what I found on MSDN. I think this might help you. The stream provider looks at the Content-Disposition header field and determines an output Stream based on the presence of a filename parameter. If a filename parameter is present in the Content-Disposition header field then the body part is written to a FileStream, otherwise it is written to a MemoryStream. This makes it convenient to process MIME Multipart HTML Form data which is a combination of form data and file content.

Categories : Dotnet

Getting Around HttpContext.Current issue
if (System.Environment.MachineName == "xxx") Although, the preferred way of doing that is to have a base web.config file, and creating XLST transforms for your different environments that change the values based on how you publish your project. For example, we have web.config, web.release.config, web.debug.config, and web.staging.config. We have different values for caching, output caching, the debug attribute, connection strings, email server settings, etc for each environment and they all get swapped out at publish time. Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs) ' Fires when the application is started Select Case LCase(System.Environment.MachineName) Case "localhost", "development_domain" DB_Environment = "DEVELOPMENT" C

Categories : Dotnet

Can not access to HttpContext.Current
Have you included the System.Web assembly in the application? using System.Web; If not, try specifying the System.Web namespace, for example: System.Web.HttpContext.Current

Categories : C#

How we Redirect one Page to AnotherPage with Server.MapPath
you don't need MapPath here, since you have relative path you can directly call Response.Redirect Response.Redirect("~/ReportPage.aspx"); Server.MapPath will return physical path of given file. For example when we need to read TEXT file inside root folder var lines = File.ReadAllLines(Server.MapPath("~/temp.txt")); But in your case no need of a Server.MapPath

Categories : C#

Cannot use Server.MapPath to access a external file
Server.MapPath works only with files that are inside the website and is used by specifying a relative location: string configFile = Server.MapPath("~/App_Data/config.xml.config"); If you want to access a file from some other location you will have to manually provide the absolute path to it: string configFile = @"c:worksome_folderconfig.xml.config";

Categories : C#

Why won't File.copy work with Server.MapPath
Server.MapPath is a secure method, and requires that you have AspEnableParentPaths set to true for your application. http://msdn.microsoft.com/en-us/library/ms524632(v=vs.90).aspx

Categories : Asp Net

Why is HttpContext.Current null after await?
Is my test flawed, or is there some web.config element I'm missing here that would make HttpContext.Current resolve correctly after an await? Your test is not flawed and HttpContext.Current should not be null after the await because in ASP.NET Web API when you await, this will ensure that the code that follows this await is passed the correct HttpContext that was present before the await.

Categories : C#

HttpContext.Current is null in Application_PreSendRequestHeaders
Did you recently upgrade from VS 2008 to VS 2012? I think you still need to upgrade the web.config file then. 1) Remove this section in the <configSections>: <sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"> <sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"> <section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefin

Categories : C#

HttpContext.Current is null for bots
You should check the Session for null like so: public static bool BrowserSupportsJS { get { if(HttpContext.Current.Session == null) return false; return (HttpContext.Current.Session["js_support"] != null && ((bool)HttpContext.Current.Session["js_support"])); } }

Categories : C#

use of timer causes HttpContext.Current to be null
HttpContext.Current only gives you the context you want when you call it on the thread that handles the incoming thread. When calling it outside of such threads, you get null. That matches your case, as Timer1_Elapsed is executed on a new thread.

Categories : Asp Net

Get AD Guid from HttpContext.Current.User
If you're on .NET 3.5 and up, you should check out the System.DirectoryServices.AccountManagement (S.DS.AM) namespace. Read all about it here: Managing Directory Security Principals in the .NET Framework 3.5 MSDN docs on System.DirectoryServices.AccountManagement Basically, you can define a domain context and easily find users and/or groups in AD: // set up domain context using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain)) { // find a user UserPrincipal user = UserPrincipal.FindByIdentity(ctx, User.Identity.Name); if(user != null) { Guid userGuid = user.Guid ?? Guid.Empty; } } The new S.DS.AM makes it really easy to play around with users and groups in AD!

Categories : Asp Net Mvc

HttpContext.Current Null in CacheItemUpdateCallback
Basically you have to create an ajax poll that calls a method that queries the cache object. You cannot update a page from a cache expiration callback as the thread that is used has nothing to do with a request object (it is part of the asp.net/iis process and not anything to do with a HttpRequest (which is where the .Context is populated)). So basically on the page you need to display the data create either a $.ajax or use an asp.net ATLAS timer (or straight .js ajax if you wish) that calls either a asmx endpoint or a WebMethod which can query the HttpContext.Current.Cache and return the appropriate string/html/json/xml/whatever data. UPDATE: There are libraries available for the server updating clients without the programmer understanding/implementing long polling/ polling techniques.

Categories : C#

What using directive do I use for Server.MapPath in a separate .cs file in WebMatrix?
You can assign the Server property to a variable to save a bit of typing: var server = HttpContext.Current.Server; var file = server.MapPath("~/SomeDirectory/Somefile"); To answer the question posed in the title of your post - the using directive you need in the class file is System.Web: using System.Web; I don't know of any "cheat sheet" as such. Experience and a growing familiarity with MSDN help, as does Resharper if you can afford it and have the full version of Visual Studio.

Categories : C#

Why HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath is different on different servers?
It gets the virtual path of the application root and makes it relative by using the tilde (~) notation. It does not says anything about the parameters of the path that you passed throught. If you look at the begining of the returned string, it is the same. I'm pretty sure that the URL in each request is different, with and without LoginUser, so the complete returned string seems different base on that, althought, for the function, they are the same.

Categories : C#

what HttpContext.Current.Request["CarName"] != null, what it is doing?
The indexer method on the Request object looks up the KeyValuePair's within Request's members. It is important to note that Request is an entire object.. not just a URL. ILSpy shows this as the implementation of the indexer method: public string this[string key] { get { string text = this.QueryString[key]; if (text != null) { return text; } text = this.Form[key]; if (text != null) { return text; } HttpCookie httpCookie = this.Cookies[key]; if (httpCookie != null) { return httpCookie.Value; } text = this.ServerVariables[key]; if (text != null) { return text; } return null; } } So, your line of

Categories : C#

HttpContext.Current vs System.Web.UI.Page.Context
If you have choice it is always better to avoid using global variables/properties of any kind in favor of more local versions to make code more self-documenting (explicit dependencies are easier to see) and testable (it is easier to pass mock/custom object than trying to set up potentially non-writable global property). In case of HttpRequest all ways you've mentioned will give you the same object. The difference is if you pass one in to your methods than you can test code much easier compared to using HttpContext.Current.

Categories : C#

HttpContext.Current.Request.Form checkbox
The cbxR1, cbxR2 should be the name of an input element, not the id. <form ...> <input type="checkbox" name="cbxR1" checked="checked" /> <input type="checkbox" name="cbxR2" checked="checked" /> </form>

Categories : C#

asp.net HttpContext.Current.Request.ServerVariables not working
Here's the method I use to get the IP address: private static string GetIPAddress() { try { if (System.ServiceModel.OperationContext.Current != null) { var endpoint = OperationContext.Current.IncomingMessageProperties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty; return endpoint.Address; } if (System.Web.HttpContext.Current != null) { // Check proxied IP address if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null) return HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] + " via " + HttpContext.Current.Request.UserHostAddress;

Categories : Asp Net

HttpContext.Current is NULL in NServiceBus MessageMutator
MutateIncoming will be called on an NServiceBus worker thread and not on an ASP.NET worker thread - hence no HTTP context. Think of it - what would you expect the HTTP context to be when you're handling an NServiceBus message? If you need something from the user's session, you'd probably need to pass some kind of session ID or correlation ID around, allowing you leave the data in the right place when the reply message gets handled.

Categories : C#

HttpContext.Current.Items after an Async operation
Cutting a long story short, it normally should. Unless you are using ConfigureAwait(false) which can have a side effect with continuation not flowing the context. Alternatively try adding this setting in your app. <appSettings> <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" /> </appSettings> UPDATE NOTE!! Initially I put false. But it must be true so that context flows.

Categories : C#

HttpContext.Current is null in custom IHttpHandlerFactory
After looking at the System.Web assembly in .NET Reflector, it appears that ReleaseHandler may be called outside of the lifecycle of a request, which means that the concept of having HttpContext.Current is not applicable. However, there are a couple of things I could suggest: If you control the implementation of the handler that GetHandler returns, you could add public or internal members to it to represent the specific data you are looking to use in ReleaseHandler. public class MyHandler : IHttpHandler { /* Normal IHttpHandler implementation */ public string ThingIWantToUseLater { get;set; } } Then in your handler factory: public class HandlerFactory : IHttpHandlerFactory { public IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTr

Categories : Asp Net

HttpContext.Current.Cache VS. SQL Table Performance
What you are describing is really : duplicating the data into a second (technically redundant) model, more suitable for query. If that is the case, then sure : have fun with that - that isn't exactly uncommon. However, before doing all that, you might want to try indexed views - it could be that this solves most everything without you having to write all the maintenance code. I would suggest, however, not to "remove caching" - but simply "make the cache expire at some point"; there's an important difference. Hitting the database for the same data on every single request is not a great idea.

Categories : Sql Server

Find specific value in HttpContext.Current.Cache
You are getting this error because the object which you are trying to iterate does not implement IEnumerable interface. It seems like en.Value is an object here (I don't have VS with me to test it right now). If it is then, you need to cast it into the appropriate type and if your cast type is a collection and does not implement IEnumerable interface, you need to call AsEnumerable() extension method by System.Linq in place. Otherwise, as I said casting it into appropriate type should work.

Categories : Dotnet

Server.MapPath returning a path with a folder that doesn’t exists
I don't believe MapPath guarantees that a path exists, it just tacks your virtual path to the context path. I think your problem is that you're using HttpContext.Current.Server.MapPath try using HttpContext.Current.Request.MapPath

Categories : Dotnet

Ninject with MVC4 conditional binding on HttpContext.Current
The problem is that your binding here resolves at compile time; whereas you need it to resolve at runtime, for every request. To do this, use ToMethod: Bind<ICustomerRepository>().ToMethod(context => TenantLookup.LookupByDomain(HttpContext.Current.Request.Url.Host.ToLower()).Foldername == "insideeu" ? new AXCustomerRepository() : new CustomerRepository()); This means that, every time the ICustomerRepository is called for, NInject will run the method using the current HttpContext, and instantiate the appropriate implementation. Note that you can also use Get to resolve to the type rather than to the specific constructor: Bind<ICustomerRepository>().ToMethod(context => TenantLookup.LookupByDomain(HttpContext.Current.Request.Url.Host.ToLower()) .

Categories : Asp Net Mvc

Is HttpContext.Current.Items thread-safe between Requests?
HttpContext Encapsulates all HTTP-specific information about an individual HTTP request. Hence each request HttpContext.Items["sameKey"] will be a different copy.

Categories : C#

Url skip second querystring parameter in HttpContext.Current.Request.Url.AbsoluteUri
You must encode url: Response.Redirect("Login.aspx?ReturnUrl=" + HttpUtility.UrlEncode(HttpContext.Current.Request.Url.AbsoluteUri)); If you are using forms autentication, you can set authentication timeout to one minute less than your session timeout. Then you don't have to code this by yourself, because ASP.NET will redirect user to login page automatically after the timeout has expired.

Categories : C#

How to use HttpContext.Current.Session in static property of a abstract class.?
Your base class Controller specifies a HttpContext property itself. So, when using it in your derived class ControllerBase, the compiler thinks you want to refer to this property of the base class. You could either make the property non-static, as wudzik suggested in the first comment. I guess this would be the cleaner way to do it. If you need to keep this property static, you have to tell the compiler, that you want to use the HttpContext class of namespace System.Web: public static string SesssionId { get { return System.Web.HttpContext.Current.Session["SessionId"]; } }

Categories : C#

Is this possible to call the System.Web.HttpContext.Current.Request.Url in C# Models function?
HttpContext.Current will only work if the code is executed within an existing HTTP context. For example this code will return null if you attempt to execute it in a unit test. It is a terribly bad practice to rely on any HttpContext specific things in your models. This property could be set in your controller (where you have access to the HttpContext) and then pass the model to your DAL and Service layers where the property will already be populated.

Categories : C#

Find key using lambda expression in HttpContext.Current.Items cache
The Items property is an IDictionary, so you'd have to do this: public IEnumerable<string> GetKey (Func<string, bool> condition) { return HttpContext.Current.Items .Cast<DictionaryEntry>() .Where(e => e.Key is string && e.Value is string && condition(e.Key as string)) .Select(e => e.Value as string); } or in query syntax: public IEnumerable<string> GetKey (Func<string, bool> condition) { return from e in HttpContext.Current.Items.Cast<DictionaryEntry>() where e.Key is string && e.Value is string && condition(e.Key as string) select e.Value as string; } Update I miss-read the question

Categories : C#

Dns.GetHostEntry(HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]).HostName returns different pcnames
Thank you very much for your great ideas, they help me out to find the real problem. A few weeks ago we migrate our network domain and the server for this particular web application was still pointing to the old DNS. Thank you very much for your help =)

Categories : Asp Net

How to download file from System.Web.HttpContext.Current.Response.BinaryWrite(byteArray); from javascript instead of C#
Use window.open('CONTROLLER_URL/STATUS_ID'); instead of an AJAX request. <a target="_blank" href="javascript:window.open('/Home/Get_Attachment_By_StatusID/12345');">Test</a>

Categories : Javascript



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.