Error 404 while accessing Handler.ashx via url - c#

I create an API to send data from server to client using ASP.NET.
I am using this guide: https://www.c-sharpcorner.com/article/how-to-send-data-from-android-to-sql-server-using-restful-ap/.
When I try to access the Handler.ashx I get ERR_CONNECTION_RESET error and I don't understand the reason.
web.config file:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<!-- To customize the asp.net core module uncomment and edit the following section.
For more info see https://go.microsoft.com/fwlink/?linkid=838655 -->
<system.webServer>
<handlers>
<remove name="aspNetCore" />
<add name="aspNetCore" path="*.ashx" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
</handlers>
<aspNetCore processPath="%LAUNCHER_PATH%" arguments="%LAUNCHER_ARGS%" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" hostingModel="InProcess" />
</system.webServer>
<connectionStrings>
<add name="ConString" connectionString="Data Source=DESKTOP-1QIGJNA;Initial Catalog=tests;Integrated Security=True" providerName="System.Data.SqlCliesnt" />
</connectionStrings>
</configuration>
Handler.ashx:
<%# WebHandler Language="C#" Class="Handler" %>
using System;
using System.Web;
using JsonServices;
using JsonServices.Web;
namespace RESTful_API
{
public class Handler: JsonHandler
{
public Handler()
{
this.service.Name = "RESTful_API";
this.service.Description = "JSON API for android appliation";
InterfaceConfiguration IConfig = new InterfaceConfiguration("RestAPI", typeof(ISAPI), typeof(SAPI));
this.service.Interfaces.Add(IConfig);
}
}
}

Related

Disallowing HTTP verbs: System.Web.HttpMethodNotAllowedHandler is never invoked

On my site, I want to disallow HTTP HEAD requests and have them answered with the 405 status code (Method not allowed). To achieve this I have the following in my web.config file:
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<remove name="TelemetryCorrelationHttpModule" />
<add name="TelemetryCorrelationHttpModule" type="Microsoft.AspNet.TelemetryCorrelation.TelemetryCorrelationHttpModule, Microsoft.AspNet.TelemetryCorrelation" preCondition="integratedMode,managedHandler" />
<remove name="ApplicationInsightsWebTracking" />
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
</modules>
<handlers>
<clear />
<add name="DenyHead" path="*" verb="HEAD" type="System.Web.HttpMethodNotAllowedHandler" />
<add name="DebugAttachHandler" path="DebugAttach.aspx" verb="DEBUG" type="System.Web.HttpDebugHandler" preCondition="integratedMode,runtimeVersionv4.0" />
<add name="StaticFile" path="*" verb="*" modules="StaticFileModule" resourceType="Either" requireAccess="Read" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,POST,DEBUG" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
<security>
<requestFiltering allowDoubleEscaping="true">
<verbs allowUnlisted="false">
<add verb="GET" allowed="true" />
<add verb="POST" allowed="true" />
<add verb="HEAD" allowed="true" />
<add verb="DEBUG" allowed="true" />
</verbs>
</requestFiltering>
</security>
</system.webServer>
Unfortunately, this doesn't work - I'm receiving bog-standard 404s instead.
Enabling failed request tracing yields the following:
20 HANDLER_CHANGED OldHandlerName
NewHandlerName DenyHead
NewHandlerType System.Web.HttpMethodNotAllowedHandler
...
61 AspNetPipelineEnter Data1 <Application_BeginRequest in my ASP.NET application>
...
135 HANDLER_CHANGED OldHandlerName System.Web.HttpMethodNotAllowedHandler
NewHandlerName System.Web.Mvc.MvcHandler
...
169 MODULE_SET_RESPONSE_ERROR_STATUS Notification EXECUTE_REQUEST_HANDLER
HttpStatus 404
This seems to show that the DenyHead handler is somehow being replaced/overridden by my MVC application, but there's no code in my app that does anything of the sort.
I've tried alternative recommendations such as the answers here, but they give the same result.
Request filtering isn't an option because the status code it returns is not configurable (it always returns a 404).
Action filters aren't an option because they won't be hit for static content, and I don't want to send everything through the MVC pipeline.
You can create action filter, and check for request method. If it is "HEAD", you can reject request by settings Result property on filterContext and set statuscode to 405 method not allowed.
Or You can check above logic for Application_BeginRequest in Global.aspx and do the same.
I wouldn't use IIS configuration as it gets you dependant on IIS, even though you might already be. Using a filter removes that dependency, just like that:
public class VerbFilter : IAsyncActionFilter
{
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
if (context.HttpContext.Request.Method == "HEAD")
{
context.Result = new StatusCodeResult(405);
}
else
{
await next();
}
}
}

WS should return only JSON not XML wrapped JSON

I have a WS which should return only JSON, however its being wrapped in a XML.
Already removed the
[WebService(Namespace = "http://www.url.com/")]
But it has no affect, my WS looks like this
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class pointer : System.Web.Services.WebService
{
[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public string HelloWorld(string name)
{
Account account = new Account
{
Email = "james#example.com",
Active = true,
CreatedDate = new DateTime(2013, 1, 20, 0, 0, 0, DateTimeKind.Utc),
Roles = new List<string>
{
"User",
"Admin"
}
};
return JsonConvert.SerializeObject(account, Formatting.Indented);
//return "Hello World";
}
the return looks like this:
This XML file does not appear to have any style information associated with it. The document tree is shown below.
<string xmlns="http://tempuri.org/">
{ "Email": "james#example.com", "Active": true, "CreatedDate": "2013-01-20T00:00:00Z", "Roles": [ "User", "Admin" ] }
</string>
my config looks like this:
<configuration>
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="500000000"/>
</webServices>
</scripting>
</system.web.extensions>
<system.webServer>
<handlers>
<add name="ScriptHandlerFactory"
verb="*" path="*.asmx"
type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
resourceType="Unspecified" />
</handlers>
</system.webServer>
<system.web>
<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>
<compilation debug="true" targetFramework="4.0" />
<httpRuntime targetFramework="4.0" />
</system.web>
<system.webServer>
<defaultDocument enabled="true">
<files>
<clear />
<add value="pointer.asmx" />
<add value="default.aspx" />
</files>
</defaultDocument>
<security>
<authorization>
<add accessType="Allow" users="?" />
</authorization>
</security>
<httpErrors errorMode="Detailed" />
<!--<handlers accessPolicy="Read, Execute, Script" />-->
</system.webServer>
Is there anyway to keep the wrappers away and just return JSON?
The ScriptService automatically serialize the result to JSON, you dont have to do it manually, otherwise it gets serialized twice. I think the content-type from the client is specifying application/xml instead of application/json?

Glimpse works locally, not on remote server

After following all the guides, SO pages and troubleshooting pages I can find I'm finally out of ideas.
I've got Glimpse working fine on my local dev server, but when I deploy my ASP.net (MVC5) app to my remote server it doesn't work - at all. /glimpse.axd gives a 404 with both LocalPolicy and ControlCookiePolicy set to ignore, and with a custom security policy that returns On in all cases. My understanding is that with ControlCookiePolicy disabled, I shouldn't need to go to /glimpse.axd to enable it - but I'm not seeing the glimpse icon on the remote server either.
Even if I go to the remote server and browse localhost to /glimpse.axd I still get a 404.
My web.config looks like this:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="glimpse" type="Glimpse.Core.Configuration.Section, Glimpse.Core" />
</configSections>
<system.web>
<compilation debug="false" />
<httpRuntime targetFramework="4.5.1" relaxedUrlToFileSystemMapping="true" />
</system.web>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<remove name="FormsAuthentication" />
</modules>
<urlCompression doDynamicCompression="true" dynamicCompressionBeforeCache="false" />
</system.webServer>
<glimpse defaultRuntimePolicy="On" endpointBaseUri="~/Glimpse.axd">
<logging level="Trace" />
<runtimePolicies>
<ignoredTypes>
<add type="Glimpse.AspNet.Policy.LocalPolicy, Glimpse.AspNet" />
<add type="Glimpse.Core.Policy.ControlCookiePolicy, Glimpse.Core" />
</ignoredTypes>
</runtimePolicies>
</glimpse>
</configuration>
This is the version off the remote server (after transform). I've trimmed it a little to remove sections like appSettings.
My GlimpseSecurityPolicy.cs looks like this:
// Uncomment this class to provide custom runtime policy for Glimpse
using Glimpse.AspNet.Extensions;
using Glimpse.Core.Extensibility;
namespace RationalVote
{
public class GlimpseSecurityPolicy:IRuntimePolicy
{
public RuntimePolicy Execute(IRuntimePolicyContext policyContext)
{
return RuntimePolicy.On;
}
public RuntimeEvent ExecuteOn
{
// The RuntimeEvent.ExecuteResource is only needed in case you create a security policy
// Have a look at http://blog.getglimpse.com/2013/12/09/protect-glimpse-axd-with-your-custom-runtime-policy/ for more details
get { return RuntimeEvent.EndRequest | RuntimeEvent.ExecuteResource; }
}
}
}
The real one does an actual check, but I get the same issue with the policy above.
I cannot seem to find any trace output anywhere on the remote server, it is logging fine on my local machine.
I am deploying using the Visual Studio publish to web feature, and I've verified that the Glimpse.Core.dll is in the bin folder.
I can't see anything in the event log that is relevant.
I've also added <add namespace="Glimpse.Mvc.Html" /> to the namespaces block of the web.config in the views folder.
I tried putting #Html.GlimpseClient() in the _Layout.cshtml file just above </body> but this renders nothing.
Anybody got any ideas?
If the glimpse.axd is returning a 404 then this means the Glimpse resource handler is not registered.
If the web.config content you show above is not trimmed to much, then it is normal that Glimpse won't do much as the Glimpse HttpModule and the Glimpse HttpHandler are not registered in the system.web and/or the system.webserver sections like this
<system.web>
<httpModules>
<add name="Glimpse" type="Glimpse.AspNet.HttpModule, Glimpse.AspNet"/>
</httpModules>
<httpHandlers>
<add path="glimpse.axd" verb="GET" type="Glimpse.AspNet.HttpHandler, Glimpse.AspNet"/>
</httpHandlers>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules>
<add name="Glimpse" type="Glimpse.AspNet.HttpModule, Glimpse.AspNet" preCondition="integratedMode"/>
</modules>
<handlers>
<add name="Glimpse" path="glimpse.axd" verb="GET" type="Glimpse.AspNet.HttpHandler, Glimpse.AspNet" preCondition="integratedMode" />
</handlers>
</system.webServer>
Maybe your transform removed to much from the local web.config?

ServiceStack not showing Metadata page

This is my first Service in ServiceStack.
public class UserServiceHost : AppHostBase
{
public UserServiceHost() : base("UserServiceHost", typeof(UserService).Assembly) { }
public override void Configure(Funq.Container container)
{
// Configure Application
}
}
protected void Application_Start(object sender, EventArgs e)
{
new UserServiceHost().Init();
}
Very simple. The file UserService is the same project and directory of the Global.Asax.
When I run the project the metadata page is not displayed. The directory listing of the site is displayed.
In fact when I insert the /metadata I receive a 404.
My project is a ASP.Net Web Application. I have included ServiceStack, everything seems ok.
What am I doing wrong ?
Thanks in advance
Please adjust your web.config like following:
<system.web>
<httpHandlers>
<add path="*" type="ServiceStack.WebHost.Endpoints.ServiceStackHttpHandlerFactory, ServiceStack" verb="*"/>
</httpHandlers>
</system.web>
<!-- Required for IIS 7.0 (and above?) -->
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<handlers>
<add path="*" name="ServiceStack.Factory" type="ServiceStack.WebHost.Endpoints.ServiceStackHttpHandlerFactory, ServiceStack" verb="*" preCondition="integratedMode" resourceType="Unspecified" allowPathInfo="true" />
</handlers>
</system.webServer>

Doesn`t run http handler in asp.net application

I want to run my httphandler, when some user get access to image file with extentions like png, jpeg, gif and other. But i get eror 404 when i try to path. I think what server try find file on a disk, but i want use alias for access to file in my handler and newer access for real phisical file path.
Example config file:
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
<httpHandlers>
<add verb="GET,HEAD" path="*.jpg" type="Startup.Shop.ImageHandler, Startup.Shop" validate="false"/>
</httpHandlers>
<authorization>
<allow users="*" />
</authorization>
</system.web>
<system.webServer>
<handlers>
<add name="ImageHandlerfor JPG" path="*.jpg" verb="GET" type="Startup.Shop.ImageHandler, Startup.Shop" resourceType="Unspecified" />
<add name="ImageHandler for GIF" path="*.gif" verb="GET" type="Startup.Shop.ImageHandler, Startup.Shop" resourceType="Unspecified" />
<add name="ImageHandler for BMP" path="*.bmp" verb="GET" type="Startup.Shop.ImageHandler, Startup.Shop" resourceType="Unspecified" />
<add name="ImageHandler for PNG" path="*.png" verb="GET" type="Startup.Shop.ImageHandler, Startup.Shop" resourceType="Unspecified" />
</handlers>
</system.webServer>
/configuration>
Example handler class:
public class ImageHandler : IHttpHandler, IRouteHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.Write("Hello World");
}
public bool IsReusable
{
get
{
return false;
}
}
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
return this;
}
}
And more - iis server configurated as classic mode
If you're in classic mode, then asp.net won't get called by IIS unless IIS knows the file type that should get mapped. In your IIS control panel, you should be able to configure the file types handled by ASP.NET. Otherwise, it's going to assume that a file type is for a physical file, which it can't find on the file system.

Categories

Resources