HttpHandler and XML files - c#

I would like to intercept any request made to the server for XML files. I thought that it might be possible with an HttpHandler. It's coded and it works... on localhost only (?!?!).
So, why is it working on localhost only? Here is my web.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
<httpHandlers>
<add verb="*" path="*.xml" type="FooBar.XmlHandler, FooBar" />
</httpHandlers>
</system.web>
</configuration>
Here is my C# :
namespace FooBar
{
public class XmlHandler : IHttpHandler
{
public bool IsReusable
{
get { return false; }
}
public void ProcessRequest(HttpContext context)
{
HttpResponse Response = context.Response;
Response.Write(xmlString);
}
}
}
As you might have seen, I'm writing the xmlString directly in the response, it's only temporary because I'm still wondering how I could give the filename instead (that's the second question ;) )
What is supposed to be written in the response is only the xml filename that will be retrieved by a flash app.
Thanks
Details :
Using IIS 6.0 on Windows Server 2003.
Edit :
When calling the page from another computer it looks like it's not getting to the HttpHandler. However, the mapping for IIS have been done correctly.

I don't have an IIS6 server at hand at the moment, but there are two steps required:
map the xml extension to ASP.NET (use the executable path from aspx extension): Setting Application Mappings in IIS 6.0
tell ASP.NET to use your custom handler: Deploying HTTP Handlers and HTTP Modules
The first step is not obvious because the Visual Studio integrated web server is mapping all requests to ASP.NET.
Other resources:
How to: Create Synchronous HTTP Handlers

if IIS is version 6.0 or previous,
handler will be ignored, because IIS handle xml extensions without calling ASP.NET process.
you can change it from IIS Manager,saying iis to use asp.net for handling XML.

Related

404 Error when accessing Web API 2 service

I have a WebAPI2 web service that works on my DEV site as well as on a local staging site, but when I push to production I get a 404 error when trying to access the same services.
Here's an example of the problem ...
// production server returns 404 Error
http://my.servername.com/AppAPI/CustomerAPI/Session/4
// local stage site works
http://localhost:100/AppAPI/CustomerAPI/Session/4
I know that there are a number of reasons why a 404 could result. Bad routes came to mind first and seem to be the source of most 404 problems that I have seen in my research. I am using WebAPI 2 Attribute routing as seen in the controller code...
public class SessionController : ApiController
{
[Route("CustomerAPI/Session/{id}")]
[HttpGet]
public string Get(int id)
{
return "value";
}
}
On IIS the site that the service is located in is set up as an "Application" (AppAPI) under another site (my_servername_com).
The site structure on IIS looks like ...
* Server
+ Application Pools
+ Sites
+ my_servername_com
+ AppAPI (application)
+ bin
- default.aspx
- global.asax
- web.config
As you can see, I have included a test page in the site; default.aspx. This page displays correctly on BOTH locations, so I know that the site is running and accessible and that at least the root url is correct. The fact that the services are accessible on the local site suggests to me that the Routes are also set up correctly.
http://localhost:100/AppAPI/default.aspx -- works
http://my.servername.com/AppAPI/default.aspx -- works
Having ruled out any coding or routing issue that I could think of, it leaves me with an environment issue of some sort. I have gone through the IIS settings on both servers and they seem the same, so I am not sure what else to look at there.
My local environment (works) ...
OS: Windows 7 Professional
IIS: IIS 7 (7.5.7600.16385)
.NET Framework : .NET 4.5 (4.5.50938)
My production environment (does not work) ...
OS: Windows Web Server 2008
IIS: IIS 7 (7.0.6000.16386)
.NET Framework: .NET 4.5 (4.5.51209)
So I am left with two possibilities I think ...
Networking issue? - I am not sure what the problem could be here. A
little outside my wheelhouse.
Some overlooked configuration?
After doing some further research I see that there are a number of issues revolving around the global.asax and WebApiConfig. As it seemed that it could be relevant I have added them here but it's important to note that this is not an MVC application.
I did not create a WebApiConfig class but created a class called "Routing.cs" that does the same thing. Which is simply to enable the attribute routing.
public class Routing
{
public static void RegisterRoutes(HttpConfiguration config)
{
// enable attribute routing
// http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2
config.MapHttpAttributeRoutes();
}
}
And of course this is simply called in the global.asax.
protected void Application_Start(object sender, EventArgs e)
{
GlobalConfiguration.Configure(Routing.RegisterRoutes);
}
Any light that someone could shed would be helpful. I am about out of ideas. the next move would be to rewrite the services in ASMX ... ugghh ... I don't want to do that!
Thanks,
G
From this link:
https://weblog.west-wind.com/posts/2011/Mar/27/ASPNET-Routing-not-working-on-IIS-70
Check that you have "runAllManagedModulesForAllRequests" as true in web.config.
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
Check order of handlers in IIS:
ExtensionlessUrlHandler-Integrated-4.0 should go before StaticFile, otherwise your api call will be handled by StaticFile resulting to 404.
IIS -> Website -> Handler Mappings -> View Ordered List
You can remove StaticFile handler at all if you don't need it in your web.config:
<handlers>
<remove name="StaticFile"/>
</handlers>
There's also a similar thread here.

How to configure the web.config to allow requests of any length

I am building a site in which i would like to create a file client side from the value of a textarea element.
I have the code in place to do this, but i am getting this error
HTTP Error 404.15 - Not Found The request filtering module is
configured to deny a request where the query string is too long.
Is there a way to override this so that I am able to process requests of any size?
If not, is there a way to generate files client side without using the filesystem/active x object?
thanks
Add the following to your web.config:
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxQueryString="32768"/>
</requestFiltering>
</security>
</system.webServer>
See:
http://www.iis.net/ConfigReference/system.webServer/security/requestFiltering/requestLimits
Updated to reflect comments.
requestLimits Element for requestFiltering [IIS Settings Schema]
You may have to add the following in your web.config as well
<system.web>
<httpRuntime maxQueryStringLength="32768" maxUrlLength="65536"/>
</system.web>
See: httpRuntime Element (ASP.NET Settings Schema)
Of course the numbers (32768 and 65536) in the config settings above are just examples. You don't have to use those exact values.
In my case ( Visual Studio 2012 / IIS Express / ASP.NET MVC 4 app / .Net Framework 4.5 ) what really worked after 30 minutes of trial and error was setting the maxQueryStringLength property in the <httpRuntime> tag:
<httpRuntime targetFramework="4.5" maxQueryStringLength="10240" enable="true" />
maxQueryStringLength defaults to 2048.
More about it here:
Expanding the Range of Allowable URLs
I tried setting it in <system.webServer> as #MattVarblow suggests, but it didn't work... and this is because I'm using IIS Express (based on IIS 8) on my dev machine with Windows 8.
When I deployed my app to the production environment (Windows Server 2008 R2 with IIS 7), IE 10 started returning 404 errors in AJAX requests with long query strings. Then I thought that the problem was related to the query string and tried #MattVarblow's answer. It just worked on IIS 7. :)
If you run into this issue when running an IIS 8.5 web server you can use the following method.
First, find the "Request Filtering" module in the IIS site you are working on, then double click it...
Next, you need to right click in the white area shown below then click the context menu option called "Edit Feature Settings".
Then the last thing to do is change the "Maximum query string (Bytes)" value from 2048 to something more appropriate such as 5000 for your needs.
Something else to check: if your site is using MVC, this can happen if you added [Authorize] to your login controller class. It can't access the login method because it's not authorized so it redirects to the login method --> boom.
It will also generate error when you pass large string in ajax call parameter.
so for that alway use type post in ajax will resolve your issue 100% and no need to set the length in web.config.
// var UserId= array of 1000 userids
$.ajax({
global: false,
url: SitePath + "/User/getAussizzMembersData",
"data": { UserIds: UserId},
"type": "POST",
"dataType": "JSON"
}}
I had a similar issue trying to deploy an ASP Web Application to IIS 8. To fix it I did as Matt and Leniel suggested above. But also had to configure the Authentication setting of my site to enable Anonymous Authentication. And that Worked for me.
I had to add [AllowAnonymous] to the ActionResult functions in my login page because the user was not authenticated yet.
If your website is using authentication, but you don't have the correct authentication method set up in IIS (e.g. Basic, Forms etc..) then the browser will be getting stuck in a redirect loop. This causes the redirect url to get longer and longer until it explodes.
For someone who experiences this while running the apps from Visual Studio, while using IIS Express, first you have to locate the applicationhost.config file being used by the application. See the answer at https://stackoverflow.com/a/41553876/1849880 on how to locate the applicationhost.config file. Then, you can change the maxQueryString value as explained above.
HTTP Error 404.15 - Not Found The request filtering module is
configured to deny a request where the query string is too long.
To resolve this problem, check in the source code whether the Form tag has a property method is get/set state.
If so, the method property should be removed.

ScriptMethod in ASPX page, called from browser, IIS6 Returning 404

I have code which works on the dev environment (my machine),
though doesn't work on IIS6
I have a method in an ASPX page which has a footprint similar to this:
[WebMethod()]
[ScriptMethod()]
public static string HelloWorld(string name)
{
return 'Hi '+name;
}
When I look at the console on the browser, I can see my script call this method, though IIS returns a 404 not found.
The script does a http POST to this url:
http://mydomain.com/myPage.aspx/HelloWorld
I am guessing it has something to do with mime types on IIS?
Found the solution to this,
The problem was caused by two things.
Firstly, I needed to add this to the Web.Config
<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>
Then , the other issue was the use of a tool for url rewriting called UrlRewritingNet
(http://www.urlrewriting.net/149/en/home.html)
One of the ways to configure this module, is to put in in IIS6 as an ISAPI filter , matching a wild card * , so if no file extension was matched, this filter would run the query.
The way I got around the second problem was to do an XML query to my service, and not a json one. Which then uses a url with a file extension when making the call.
Hope this helps

Invalid Webmethod name

I created a web method but when i go to the site and type for example http://mysite.com/services/Amounts/GetAmount it returns an error Internal Server Error 500. After investigating the issue in event logs etc,, it says GetAmount invalid method name. but i know the mame is fine
[WebMethod(EnableSession=true)]
public string GetAmount(Amounts amts)
{
//some logic here to add to the database.
}
What are the possible issues that I have to look into when this type of error shows?, I checked all the references and everything is named properly "GetAmount".
What are you trying to do here? You need to post more code and web.config. Which version of .NET you are using here? All this information may get you the better answer.
Firstly, your URL http://example.org/services/Amounts/GetAmount does not seems to be correct - there has to be .asmx somewhere unless you are using ASP.NET routing or some url rewriting.
Assuming that your routing/re-writing is indeed working correctly:
in general, if its a normal SOAP Web Service then enable HTTP get -
<webServices>
<protocols>
<add name="HttpGet" />
<add name="HttpPost" />
</protocols>
</webServices>
If you are trying create a service callable from script (ScriptService) then for asmx service, you need to mark the method as ScriptService and you may need to adjust web.config based on your .NET version. Also you need to enable HTTP GET - for example,
[ScriptMethod(UseHttpGet = true)]
public string GetAmount(Amounts amts)
You may also need to adjust Response Format whether you want JSON or XML.

How to increase the POST size for an ASMX web service?

Background
I am developing an ASP.Net server side control that needs to talk to an ASMX web service. The server side control uses a WebClient object to talk to the web service, since it needs to be reused often in various application, and to make it easier on the developers, they are not required to create a service reference to the web service.
Implementation
During the use of the control, it is requires the sending of a serialised object to the web service. The object is serialised using the XmlSerializer and the resulting XML string is then compressed using the chilkat compression library. The web service call for the control looks as follows:
webClient.UploadStringAsync(new Uri(serviceHost + serviceMethod), "POST", sendData)
The content of sendData (string) is compressedResponse={CompressedData}.
The web service has a method defined as follows to receive the data and then decompress the string value using the chilkat library before de-serialising the object using the XmlSerializer.
public void SaveResponse(string compressedResponse)
The communication between the control and the service is working. Initially there were no settings or binding defined in the web.config for any of the above. After initial searching I did add
<httpRuntime maxRequestLength="20480"/>
to both the client and server web.config files. This has made no difference.
Problem
Compressed or uncompressed the data being posted to the web service in the sendData variable is to big for a normal POST request, and is corrupted. This is confirmed when checking the last few characters of the string before and after it being posted to the server in compressed format, and uncompressed, the Xml document is missing the last root tag when checking in the debugger. The string can't be decompressed and therefore the service call fails every time.
How do I increase the POST size for the WebClient request to ensure that the full string is received by the server?
I have looked at the various option on Google, but none are giving me a good enough sample of where to make the changes, or samples of what the changes need to look like. I am completely lost as to whether the change needs to be made on the server or the consuming website, and since there are no binding defined for this, how to create a binding in the web.config for an ASMX HTTP service call.
I believe you must be hitting ASP.NET max request length limit. That you can modify via config file such as:
<system.web>
<httpRuntime executionTimeout="240" maxRequestLength="20480" />
</system.web>
maxRequestLength value is in KB, so above setting would allow 20 MB. You can also apply the setting only to selected URLs using location tag e.g.
<location path="yourservice.asmx">
<system.web>
<httpRuntime executionTimeout="240" maxRequestLength="20480" />
</system.web>
</location>
There seems to be no way to change the POST size for a ASMX Web Service when only HttpPost is enabled.
The solution in the end was to switch the service to running HttpSoap and create a service reference to the assembly containing the control. Once done the binding is created using code in the control once the endpoint is set via a property.

Categories

Resources