ServiceStack not showing Metadata page - c#

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>

Related

Error 404 while accessing Handler.ashx via url

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);
}
}
}

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();
}
}
}

Add security headers to help protection from injection attacks in c# asp.net

I have a C# asp.net application.It was sent to security assessment and below were the risks.
-Missing "Content-Security-Policy" header
-Missing "X-Content-Type-Options" header
-Missing "X-XSS-Protection" header
-It was observed that server banner is getting disclosed in HTTP response.
-It was observed that service version is getting disclosed in HTTP response.
I have the below code in the web.cofig file
<httpProtocol>
<customHeaders>
<remove name="X-Powered-By"/>
<add name="X-Frame-Options" value="DENY"/>
<add name="X-XSS-Protection" value="1; mode=block"/>
<add name="X-Content-Type-Options" value="nosniff "/>
</customHeaders>
</httpProtocol>
I thought this will add the headers. But the security team says the issue is not fixed. Is there any alternate for this.And for the Banner disclosure, I don't have access to server. can I fix this within the application.
After research I found this: Inside Global.asax I have this code:
protected void Application_PreSendRequestHeaders()
{
// Response.Headers.Remove("Server");
Response.Headers.Set("Server", "My httpd server");
Response.Headers.Remove("X-AspNet-Version");
Response.Headers.Remove("X-AspNetMvc-Version");
}
protected void Application_BeginRequest(object sender, EventArgs e)
{
var app = sender as HttpApplication;
if (app != null && app.Context != null)
{
app.Context.Response.Headers.Remove("Server");
}
}
Is this the correct fix. Please help
Adding and removing headers during Application_BeginRequest always leads to headaches with your server complaining about not being able to do things after headers are set.
Typically "X-AspNet-Version" and "X-AspNetMvc-Version" are IIS custom headers and removing them depends on the verion of IIS you are using.
With new versions of IIS you can set it in Web.Config:
<system.web>
<httpRuntime enableVersionHeader="false" />
</system.web>
In older version you need to use IIS manager (see https://www.google.com/search?q=iis+remove++X-AspNet-Version&ie=utf-8&oe=utf-8):
You can remove the MVC header in app_start in Global.asax
MvcHandler.DisableMvcResponseHeader = true;
Your web.config should work fine:
<add name="X-Frame-Options" value="DENY"/>
<add name="X-XSS-Protection" value="1; mode=block"/>
<add name="X-Content-Type-Options" value="nosniff "/>
If not, Application_PreSendRequestHeaders is an appropriate place to add or remove headers well.
HttpContext.Current.Response.Headers.Add("X-Frame-Options", "DENY");
HttpContext.Current.Response.Headers.Add("X-XSS-Protection", "1; mode=block");
HttpContext.Current.Response.Headers.Add("X-Content-Type-Options", "nosniff");
HttpContext.Current.Response.Headers.Remove("Server");
You can use the web developer console on your web browser (usually opened by hitting F12) and click on the network tab to see what headers the server is sending.
Ensure you add the httpProtocol in the system.webServer as shown below:
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="X-Frame-Options" value="DENY" />
<add name="X-Xss-Protection" value="1; mode=block" />
<remove name="X-Powered-By" />
</customHeaders>
</httpProtocol>
</system.webServer>
To remove the "server" header, add the code below in your Global.asax file
protected void Application_PreSendRequestHeaders()
{
Response.Headers.Remove("Server");
}
You can add any header globally using web.config e.g.
<system.webServer>
<httpProtocol>
<customHeaders>
<remove name="X-Powered-By" />
<add name="Cache-Control" value="no-store" />
<add name="X-XSS-Protection" value="1; mode=block" />
<add name="X-Content-Type-Options" value="nosniff" />
<add name="Strict-Transport-Security" value="max-age=31536000" />
</customHeaders>
</httpProtocol>
</system.webServer>
Refer : Adding Custom Headers Globally

404 after upgrading ServiceStack from 3.9.8 to 3.9.70 (new API)

We've been using a legacy version (3.9.8) of ServiceStack for a while now and I decided to try an upgrade to the latest version (3.9.70) and while it was a clean, no hassle package upgrade - everything compiles and runs - every service URL now returns a "Handler for Request not found" 404 result.
An example of a URL that used to work:
http://somewebserver.com/services/servicestack/jsv/syncreply/getuser
We use the old API (IService<T>) and make no use of REST routes or anything of the sort.
The ServiceStack application runs inside an ASP.NET MVC 3 web application, which lives on the URL http://somewebserver.com/management/controller/action. It doesn't seem like it's interfering as it's been configured to ignore the ServiceStack route:
routes.IgnoreRoute("servicestack/{*pathInfo}");
The ServiceStack code is definitely running as going to http://somewebserver.com/services/servicestack redirects me to the metadata page, which works.
I've tried following these steps:
https://github.com/ServiceStack/ServiceStack/wiki/Run-servicestack-side-by-side-with-another-web-framework
But it doesn't seem to make a difference.
What I changed in the config to try and make this work:
1) Removed this old line in system.webServer/handlers
<add path="servicestack" name="ServiceStack.Factory" type="ServiceStack.WebHost.Endpoints.ServiceStackHttpHandlerFactory, ServiceStack" verb="*" preCondition="integratedMode" resourceType="Unspecified" allowPathInfo="true" />
2) Added this location section:
<location path="servicestack">
<system.web>
<httpHandlers>
<add path="*" type="ServiceStack.WebHost.Endpoints.ServiceStackHttpHandlerFactory, ServiceStack" verb="*"/>
</httpHandlers>
</system.web>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<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>
</location>
3) Added this in the app host setup:
this.Config.ServiceStackHandlerFactoryPath = "servicestack";
Calling the URL fails for both POST and GET, which used to both work.
This is all running under IIS 8.
I'd love to know what's going on here, so we can finally upgrade and live in 2013 :)
Apparently, the fix was in how we enabled the ServiceStack features. I didn't make the change myself, but these are the fixes:
Removed from AppHost:
this.Config.EnableFeatures = Feature.Metadata | Feature.Jsv | Feature.Json;
this.Config.ServiceStackHandlerFactoryPath = "servicestack";
Replaced by:
Feature disableFeatures = Feature.Soap;
SetConfig(new EndpointHostConfig
{
ServiceStackHandlerFactoryPath = "servicestack",
EnableFeatures = Feature.All.Remove(disableFeatures),
DebugMode = false,
WriteErrorsToResponse = false,
DefaultContentType = ContentType.Jsv,
AllowJsonpRequests = false
});

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