Are ASMX Web Service Enable Session and ResponseFormat Required - asp.net

I have been asked to change a legacy .asmx web service and there are a few issues I would appreciate some guidance on.
The web methods are decorated like this:
[WebMethod(EnableSession = true), ScriptMethod(ResponseFormat = ResponseFormat.Json)]
In my particular method, I am returning data from a database, which I return as a list of to of objects using JSON.
I noticed that the JSON is still returned without the: ScriptMethod(ResponseFormat = ResponseFormat.Json part.
In that case:
can I safely remove this from here?
if it still works, does that mean it will be configured elsewhere in a base class or config file perhaps?
What is the purpose of the (EnableSession = true) and is it required if the service does not update the data and the read data is rarely changed?
Sorry for the basic rather vague questions but I've not worked with .asmx web services before. Can someone point me in the right direction please?
Thanks

EnableSession = true allows you to access the Session collection, which is part of the HttpContext.Current.Session. If the code in your web method does not use the Session collection, then yes it is safe to remove, but if it does use the Session collection, then removing this attribute will cause your web service logic to throw an exception, because it will not have access to the Session collection.
ScriptMethod(ResponseFormat = ResponseFormat.Json) is explicitly defining that this web method will return JSON, but since JSON is the default return type, then removing it does not matter. So the short answer is, yes it is fine to remove this, but it will not hurt to leave it there (in fact I would argue that is better to because it explicitly states this thing is returning JSON data).

AS #Karl already said if you need to access Session in webmethod, you've to decorate your method with the said attribute.
Now I've seen people complaining about webmethod not returning JSON response on SO and Asp.net official forum even though they have decorated their method with
ScriptMethod(ResponseFormat = ResponseFormat.Json)
because they might have missing configuration in web.config.
I would suggest you to go through Dave Ward's below articles that may help you to understand what needs to be done to return JSON response with ASMX:
ASMX and JSON – Common mistakes and misconceptions
ASMX ScriptService mistake: Installation and configuration

Related

Access HttpContext.Current.Session in Nancy Module

I've read a lot of answers saying to just use the built-in Nancy Session/User object, but this isn't an option in my case.
Using WCF I was able to access the ASP.Net Session["SomethingStuffedIntoSessionFromAWebForm"] by enabling aspNetCompatibilityEnabled in the web.config (other stuff had to been done too, probably), but I can't seem to figure out how to get a handle on the System.Web.HttpContext.Current.Session (or anything else in the current context) from within a Nancy module.
My 1st thought was to inject it in the bootstrapper but I can't even get a handle on the System.Web.HttpContext.Current.Session there either. Any ideas?
Edit
I ended up just stuffing an encrypted version of my desired session object into a cookie upstream and checking/validating against it in the module's BeforePipeline... not too crazy about this approach, but it suits my needs for now.
As far as I can tell, when a Nancy module handles a request, it bypasses the Asp.Net pipeline, so while I actually do have access to HttpContext.Current, Session is not populated.
Inherit IRequiresSessionState to enable Asp.net Session.
public class NancyAspHttpRequestHandler
: NancyHttpRequestHandler, IRequiresSessionState
{
}
and use NancyAspHttpRequestHandler in handler registration, this can be possible using Nancy.AspNet hosting.
This will solve the problem

Is it possible to access HttpContext.Current.Session from Web API

Is it possible to access HttpContext.Current.Session through a WebAPI ? can we make it inheriting IRequiresSession?
I have a generic handler doing a Session set after an API call which I want to remove.
public void AccountController : ApiController, IRequiresSessionState
{
public void Login()
{
setsession(){}
}
}
Technically, yes, although I'd really advise against this practice - a REST API should be completely stateless (cookies and other client-side state is OK).
If you absolutely must do this, you can grab the HTTP context like so:
var context = Request.Properties["MS_HttpContext"] as HttpContext;
At which point you just use its Session property to get the session.
Note that this breaks certain contracts assumed by System.Net.Http - specifically it means your API controllers can never be self-hosted because they're coupled to ASP.NET. If you're OK with this, and with the fact that your API controllers may not work properly from a web farm unless you re-architect everything to use distributed sessions - well then, go for it.
P.S. It is also possible to use IRequiresSessionState, but you can't use it on the controller itself, you need to use it on an HttpControllerHandler and set it as the RouteHandler. The approach is discussed in this MSDN thread. Again, I can't recommend strongly enough against this idea, it violates the basic principle of a Web API - but, if you've got a really good reason for it, then it's another option which is a bit more reusable.
Casting it as HttpContext did not work for me using Web Api 2.1. However I could use HttpContextWrapper.
var context = Request.Properties["MS_HttpContext"] as HttpContextWrapper;
Yes - although not recommended. Here's a working answer based on the answers above (for WebAPI version 2.x)
var context =(HttpContextWrapper)Request.Properties["MS_HttpContext"];
var sessionId = context.Request.Params["ASP.NET_SessionId"];

SpringMVC session managament

I have a simple SpringMVC v3.2.2 controller that does the following:
#RequestMapping(value = { "/login" }, method = RequestMethod.GET)
public String login(WebRequest request) {
request.setAttribute("myattr", "myvalue", SCOPE_SESSION);
}
I'm using the WebRequest object in order to save attributes in the session scope. The SCOPE_SESSION is an integer stating that I want to use it in the session scope. More info on the API is here:
WebRequest API
I assume that it means that I'm adding some attribute that will be saved in the session scope. Session, I assume, will be deleted when the server restarts, during my tests, because I don't want to have any session persisted locally. Unless some default configuration keeps it persisted.
For some reason, the session doesn't get deleted even after tomcat restart(I'm using Tomcat V7, default configuration), meaning that it is persisted for some reason. Tried to find more documentation explaining how to disable it, but could not.
What Am I missing ? if the attribute is saved in the session scope, as the API states, should it get deleted if I restart the Tomcat Server ?
Thanks in advance,
Elad.
I have edited the original question, which was not so clear. Sorry.
Problem solved. I totally missed that the session management is controlled by Tomcat.
The solution was to edit the Tomcat 7 context.xml configuration file and make sure it has the following element :
This disables the session persistence for good. Didn't really think that this is how it works by default. Thank you anyway.

How do I completely control ASP.NET WCF return output?

I have an ASP.NET WCF .svc interface which is accepting a POSTed form. I cannot control the POSTing client at all (which happens to be the IBM Lotus Forms Viewer application), but its behavior is that it POSTs itself to a URL of my choosing and the response is popped up in Internet Explorer as a locally served temporary file with an extension controlled by the mime-type.
I am new to WCF REST services, but I am having a hard time controlling the response, which keeps getting wrapped in XML tags. Is there a way to turn off all output wrapping and control exactly what is returned from the WCF operation?
I can point the form to something other than a WCF service (like an .aspx file), but I thought it would be useful at least to learn how the formatting is controlled before I made that decision.
[EDIT] For clarification, my current service interface prototype looks like this:
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "/AF1067/SubmitForm",
BodyStyle = WebMessageBodyStyle.Bare)]
public string AF1067_SubmitForm(System.IO.Stream fileContents) { ... }
[EDIT] User #Kon found this link which had the answer -- if I return a System.IO.Stream, the response will stop being wrapped.
Continuing from our comments, I still think this may have something to do with the requestor's settings. Perhaps the bare POST which doesn't specify a content type setting defaults to the wrong one? Try to explicitly set it to "application/json" or "application/json; charset=utf-8" Just throwing ideas out there.
The other thing to make sure of is that your service method's ResponseFormat is set to JSON as well.
Btw, nice method name. ;)

Best way to perform authentication on every request

In my asp.net mvc 2 app, I'm wondering about the best way to implement this:
For every incoming request I need to perform custom authorization before allowing the file to be served. (This is based on headers and contents of the querystring. If you're familiar with how Amazon S3 does rest authentication - exactly that).
I'd like to do this in the most perfomant way possible, which probably means as light a touch as possible, with IIS doing as much of the actual work as possible.
The service will need to handle GET requests, as well as writing new files coming in via POST/PUT requests.
The requests are for an abitrary file, so it could be:
GET http://storage.foo.com/bla/egg/foo18/something.bin
POST http://storage.foo.com/else.txt
Right now I've half implemented it using an IHttpHandler which handles all routes (with routes.RouteExistingFiles = true), but not sure if that's the best, or if I should be hooking into the lifecycle somewhere else?
I'm also interested in supporting partial downloads with the Range header. Using
response.TransmitFile(finalPath);
as I am now means I'll have to do that manually, which seems a bit lowlevel?
Many thanks for any pointers.
(IIS7)
I think having a custom handler in the middle that takes care of this is exactly how you should be doing it.
TransmitFile is the lightest-weight programmatic way to serve a file that I am aware of.
However, you might not need to write your own HttpHandler. You can use the MVC handler and just dedicate a controller action to the job. Something like:
http://storage.foo.com/Files/Download/SomeFileIdentifier
...routing to...
public FilesController
{
public ActionResult Download(string id)
{
//...some logic to authenticate and to get the local file path
return File(theLocalFilePath, mimeType);
}
}
The File() method of controller uses TransmitFile in the background, I believe.
(PS, If you want shorter URLs, do it via custom routes in global.asax.)

Resources