i have a wcf service deployed in iis and running. then i have created the http handlers as ny extending IHttpHandler class and in web.config file added entry as below
<configuration>
<system.web>
<httpHandlers>
<add verb="*" path="*.sync" type="MyHandler.SyncHandler, MyHandler" />
</httpHandlers>
</system.web>
</configuration>
and in the begin method of handler i have set the value in both threadlocal and cookie as
ThreadName.Value = "sample";
and
httpCookie userCookie = new HttpCookie("Cookiename");
userCookie.Value = "sample";
context.Response.Cookies.Add(userCookie);
and while retrieving those values inside wcf service application i am getting null values from both cookies and thread local.
the code which i used was
return (String)ThreadName.Value;
i do not know where i went wrong or the approach which i used is correct!
waiting for your valuable suggestions and comments
Related
Can't get session variables working, I've tried all the solutions I could find online.
On page 1, I call the following in the c# model
HttpContext.Current.Session["lol1"] = "123";
Later on I use an ajax call to return this session variable to me in the c# model,
return HttpContext.Current.Session["lol1"].ToString();
In javascript, I pick it up in the ajax success function and put it in an alert box with alert(e);
I get an null object reference error. Seems like my variable didn't save into the session. This all works fine on localhost via debug, including the alert.
Things I have tried (currently set):
-DefaultAppPool setting Maximum Worker Processes: 1
-IIS manager->ASP->Services->Session Properties->Enable Session State:true
-IIS manager->Session State->In process
-In my solution web.config:
<system.web>
<sessionState mode="InProc" timeout="25"></sessionState>
</system.web>
<system.webServer>
<modules>
<remove name="Session" />
<add name="Session" type="System.Web.SessionState.SessionStateModule"/>
</modules>
</system.webServer>
Try setting the SessionStateBehavior in your controller. For example:
[SessionState(System.Web.SessionState.SessionStateBehavior.ReadOnly)]
It is recommended to use ReadOnly if you only need to read from Session and not write to it to prevent blocking.
Link to Microsoft's SessionStateBehavior enumeration.
(for more info on ASP.NET's blocking when controllers use writable sessions see this link: Does Session State read/write everything when you access with DynamoDB)
Hope this helps!
Regards,
Ross
I have a very simple NancyFX module which I simply want to echo the results of an API call back to the sender.
I am using a facade which converts incoming XML to JSON before handing it off to the Nancy endpoint. This facade changes the content to JSON correctly as I can test it using the echo service for the api and can see the response.
However, because the facade removes the content-length header and sets transfer-encoding to chunked, the Request.Body is always empty in my Nancy module.
Is there a configuration needed to enable support for Chunked encoding in NancyFX?
I am hosting on IIS 7 currently, but have access to IIS 8 as well.
I can see that using OWIN hosting it is possible to enable chunked transfer using HostConfiguration, but due to other factors I cannot use OWIN hosting and rely on IIS hosting.
I have enabled chunked transfer on IIS with the command:
appcmd set config /section:asp /enableChunkedEncoding:True
My web.config is currently:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.5.1" />
<httpHandlers>
<add verb="*" type="Nancy.Hosting.Aspnet.NancyHttpRequestHandler" path="*" />
</httpHandlers>
<httpRuntime targetFramework="4.5.1" />
<webServices>
<protocols>
<add name="HttpGet" />
<add name="HttpPost" />
</protocols>
</webServices>
</system.web>
<system.webServer>
<modules>
<remove name="WebDavModule" />
</modules>
<handlers>
<remove name="WebDAV" />
<add name="Nancy" verb="*" type="Nancy.Hosting.Aspnet.NancyHttpRequestHandler" path="*" />
</handlers>
<validation validateIntegratedModeConfiguration="false" />
<httpErrors existingResponse="PassThrough" />
</system.webServer>
</configuration>
The module itself is very simple and consists of:
Post["/"] = parameters =>
{
var traceRef = Guid.NewGuid();
var body = this.Request.Body.AsString();
Logger.Trace("Trace ref: {0}, request inbound.", traceRef);
Logger.Trace(body);
AuthRequest auth = new AuthRequest();
try
{
auth = this.Bind<AuthRequest>();
}
catch (Exception ex)
{
Logger.Error("Trace ref: {0}, error: {1}. Exception: {2}", traceRef, ex.Message, ex);
}
var responseObject = new
{
this.Request.Headers,
this.Request.Query,
this.Request.Form,
this.Request.Method,
this.Request.Url,
this.Request.Path,
auth
};
return Response.AsJson(responseObject);
};
My first thought when reading this was Transfer-Encoding is only meant for responses not requests. Looking at the list of HTTP header fields, Transfer-Encoding is only listed under Response Fields. But the spec doesn't mention request or response just sender and recipient. Now I'm not so sure.
Anyway, the ASP.NET hosting code explicitly excludes the body if the content length is 0, but the self-hosting code doesn't seem to have the same restriction. I'm not sure if this difference is intentional. You could remove the if statement that checks the content length and send a PR to the Nancy team. See what they come back with.
Im running a website on WindowsServer 2008 R2, and IIS 6.1 sp1
I created an empty ASP.NET 4.0 web application, and added an http handler to it. The job of the handler will be to redirect incoming calls to other sites based on a tokenid passed in the querystring (from a federated single sign on provider).
To test the connection, I am just parsing the token into a Dictionary and writing the information to the context.Response.
The handler works on my machine, but when I deploy it, I get 500 and 403 errors.
I get 500 errors when I make the application pool ASP.NET 4.0 Integrated, I get 404 errors when make the application pool ASP.NET 4.0 Classic
If I add a test.htm to the directory, I can access the test.htm and see its contents, but I would be expecting to see the output from the handler, so it makes me think it cant find the handler.
Here is the web.config followed by the code
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
<httpHandlers>
<add verb="*" path="*"
type="RedirectSite.RedirectHttpHandler, RedirectSite, Version=1.0.0.0, Culture=neutral" />
</httpHandlers>
</system.web>
<configuration>
public class RedirectHttpHandler : IHttpHandler
{
public RedirectHttpHandler()
{ }
public void ProcessRequest(HttpContext context)
{
// check for tokenid in querystring
string tokenid = context.Request.Params["tokenid"];
string agentid = context.Request.Params["agentid"];
Dictionary<string,string> tokenItems = TokenParser.Parse(tokenid, agentid);
context.Response.Clear();
context.Response.Write("<b>Token Information</b><br/><br/>");
foreach (KeyValuePair<string, string> item in tokenItems)
{
context.Response.Write(String.Format("{0} : {1}<br/>",item.Key,item.Value));
}
}
public bool IsReusable { get; private set; }
}
Turns out that the ISAPI/CGI settings for the site were preventing 4.0 - once enabled, the site worked
I used a sql server session mode between two web applications.
The session id is created in the ASPState database. I need to share the session id from first application to second without using querystring and cookies. I followed the steps from this link. Below is the code.
In both apps (web.config)
<add name="DBConnection" connectionString="Data Source=localhost;DataBase=ASPState;Integrated Security=True;uid=sa;pwd=password-1" providerName="System.Data.SqlClient"/>
<sessionState mode="SQLServer" sqlConnectionString="DBConnection" allowCustomSqlDatabase="true" regenerateExpiredSessionId="false" cookieless="false" timeout="1" ></sessionState>
<machineKey validationKey="566A547C407CB0C47ABAEC581B8B90C45E15039806352E4611B35E0FB70C1C096350A4BBAE816191331DCA55874D3F96B41FFDED4C6A913591684A90825F53A0" decryptionKey="B299127DFC22648C2EF92D7EDF2E4960277F562C60F3BDE4A4C3BFDFEA602FDF" validation="SHA1" decryption="AES" />
<modules runAllManagedModulesForAllRequests="true">
<add name="BasicAuthenticationModule" type="UserAuthenticator" />
</modules>
In first app Home.aspx.cs
protected void imgBTN_Click(object sender, EventArgs e)
{
string sessionKey = HttpContext.Current.Session.SessionID;
//How to transfer the same session id to the second application
Response.Redirect("http://localhost:43392/PartnerHome.aspx"");
}
I got the session key from ASPState database. But how to pass from the same session id to the second application ?
You can use SessionManager to set the ID to whatever you want in the target site. You just need to pass it via querystring GET or form POST from one to the other:
Source
Response.Redirect("http://localhost:43392/PartnerHome.aspx?SessID="
+ Session.SessionID);
Target
string sessionId = Request.QueryString["SessId"];
bool redirected = false;
bool isAdded = false;
new System.Web.SessionState.SessionIDManager().SaveSessionID(
HttpContext.Current, sessionId, out redirected, out isAdded);
See SessionIDManager on MSDN
I am having quite a few problems with custom extensions and intercepting existing handlers.
What am I trying to do
Based upon persisted options, I would like all 'virtual' extensions to be handled by set handlers. All pages are dynamically built, and no actual files exist on the site. The site populates the content, forms the html output and returns it as the web result.
This is required as I am setting up a fat/thin relationship between 2 servers. The thin server will simply pass on the request to the fat server - where the request is processed and response issued back down the line.
The project is for a dynamic multi-domain content management system. The thin server may not be .net compatible (hence the external request), but will be .net optimised (hence the need for handlers).
The Problem
What I want is to re-route existing extensions - aspx; php; html.
I have achieved this in my local environment using a custom HttpModule which sets the appropriate handler. I have explored setting the tag in config, but the the extensions are re-routed using dynamic rules that are persisted.
As mentioned, this solution works on localhost.
When uploaded, the .Net extensions are handled by the module correctly but any custom extensions or non-.net extensions return a 404 error.
Seeking an alternative, I have experimented with routing within Global, but this dis not work either.
I have also attempted to use to register the custom extensions... but each are met with the same result - 404 not found.
Global Routing attempt:
public class Global : System.Web.HttpApplication
{
void Application_Start(object sender, EventArgs e)
{
RegisterRoutes(RouteTable.Routes);
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.Add(new Route("{action}.sqs", new SqlRequestHandler()));
}
.Config (for handler and module attempt)
<system.web>
<compilation debug="true" targetFramework="4.0" />
<httpRuntime requestValidationMode="2.0" />
<customErrors mode="Off"/>
<httpHandlers>
<add path="*.sqs" verb="*" type="CmsMapper.VirtualHandler, CmsMapper" />
<add path="*.sql" verb="*" type="CmsMapper.VirtualHandler, CmsMapper" />
</httpHandlers>
<httpModules>
<add name="SisBerCMS" type="CmsMapper.VirtualModule, CmsMapper" />
</httpModules>
</system.web>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
<modules>
<add name="SisBerCMS" type="CmsMapper.VirtualModule, CmsMapper" />
</modules>
<handlers>
<add path="*.sqs" verb="*" type="CmsMapper.VirtualHandler, CmsMapper" name="sqsHandler" />
<add path="*.sql" verb="*" type="CmsMapper.VirtualHandler, CmsMapper" name="sqlHandler" />
</handlers>
</system.webServer>
Custom Module (CmsMapper.VirtualModule)
if (extentionMap != null)
{
// note that extentionMap.ExtentionType is a predetermined enum
switch (extentionMap.ExtentionType)
{
// If the extention is banned then pass back a generic message
case ExtentionType.Banned:
this.WriteTextResponce("Invalid extention detected:" + extentionMap.Extention);
break;
// Remap .Ajax requests to the ajax handler
case ExtentionType.Ajax:
this._app.Context.RemapHandler(new AjaxHandler());
break;
// Remap session query or sql requests to the sql handler
case ExtentionType.SessionQuery:
this._app.Context.RemapHandler(new SqlRequestHandler());
break;
// if the extention is not ignored, re map to the virtual page handler
default:
bool isManagementServer = this._app.Context.Request.Url.Authority != VirtualModule.RESPONSE_SERVER;
bool isPostRequest = !String.IsNullOrEmpty(this._app.Context.Request.Form[HtmlRequest.RequestOrigin]);
bool isGetRequest = !String.IsNullOrEmpty(this._app.Context.Request.QueryString[HtmlRequest.RequestOrigin]);
bool isIgnored = extentionMap.ExtentionType == ExtentionType.Ignore;
if ((isPostRequest || isGetRequest) && !isIgnored)
{
this._app.Context.RemapHandler(new VirtualHandler());
}
else
{
this._app.Context.RemapHandler(new ExternalRequestHandler());
}
break;
}
}
All the handlers are pretty standard implementing the following:
public class SqlRequestHandler : IHttpHandler, IRequiresSessionState, IRouteHandler
Again, the preferred method - HttpModule - works on my localhost machine. This could be a server config issue (in which case I'm looking for a work around), but the fact that the .net extensions are being handled is strange - as this would imply that issues with medium trust should not apply, however issues regarding extension handling on the server may take priority over the .net application.
The server is shared hosting (therefore I am unable to alter the machine.config files), is IIS6 using 4.0.
Thank you for any suggestions on how to resolve this issue.
Mike
You need to configure web site in IIS 6.0 to route all extensions (including extensionless paths known as wildcard extension mapping) to ASP.NET ISAPI dll (and disable the check for file exists).
You can of course do this mapping selectively only for those extensions that you want to route via ASP.NET code. But wildcard mapping will be more useful in case you don't have predefined set of extensions.
In the absence of such mappings, IIS will not forward requests for unknown extensions to ASP.NET (and routing code will not even come into picture) - rather IIS will pass the extension to default (static file) handler that will issue 404 if file is not present.
See this article that describes these steps (for ASP.NET MVC but the same applies to your case): http://haacked.com/archive/2008/11/26/asp.net-mvc-on-iis-6-walkthrough.aspx
Near the end of article, author has given how to add wildcard script map