How to ignore a route with self-hosted ServiceStack - servicestack

I am currently working on a solution where we have a self-hosted ServiceStack layer running, but the problem is that I keep getting errors when I access it from the browser and the browser tries to get the favicon. As far as I can see there is no option of ignoring a specific route when running self-hosted?
I would have imagined something like
Routes.Ignore("favicon*")
a bit like the
Routes.Add<Foo>("/foo")
in my AppHost Configure method

In my web.config I like to have something like this
<handlers>
<add verb="*" path="*.*" type="System.Web.StaticFileHandler" name="files" />
<add path="*" name="ServiceStack.Factory" type="ServiceStack.WebHost.Endpoints.ServiceStackHttpHandlerFactory, ServiceStack" verb="*" preCondition="integratedMode" resourceType="Unspecified" allowPathInfo="true"/>
</handlers>
That way all files with an extension get handled by IIS and means you don't have to go all the way through the aspnet pipeline to server up a 404. It also means you don't log a load of 404s in your servicestack application.

Unlike MVC which uses a Http Module to process and hijack all requests, ServiceStack is built-on ASP.NET's raw IHttpHandler interfaces. This means ServiceStack must handle any request matching the ServiceStack handler path (e.g. / or /api) by returning an IHttpHandler and isn't able to Ignore them like they do in MVC.
You can however catch and handle all unhandled requests by registering a handler in IAppHost.CatchAllHandlers, e.g:
appHost.CatchAllHandlers.Add((httpMethod, pathInfo, filePath) => {
if (pathInfo.StartsWith("favicon"))
return new NotFoundHttpHandler();
});

Just to append to #antonydenyer's answer. His solution seems to work also when combining owin with servicestack3.
<handlers>
<add path="auth/*" name="Microsoft.Owin.Host.SystemWeb" type="Microsoft.Owin.Host.SystemWeb.OwinHttpHandler, Microsoft.Owin.Host.SystemWeb" verb="*" preCondition="integratedMode" resourceType="Unspecified" allowPathInfo="true" />
<add path="*" name="ServiceStack.Factory" type="ServiceStack.WebHost.Endpoints.ServiceStackHttpHandlerFactory, ServiceStack" verb="*" preCondition="integratedMode" resourceType="Unspecified" allowPathInfo="true" />
</handlers>
Here SS is handling every request except /auth. Auth is mapped to Identityserver3 using owin.

Related

Seeding DB with Entity Framework 6.1.3

I'm new to web dev in general and new to .Net. As such I started following this tutorial (using vs 2015, MVC 5, EF 6.1.3): http://www.asp.net/mvc/overview/getting-started/getting-started-with-ef-using-mvc/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application
and applying it to a test app I wanted to make for fleet management. I created my seeding class, and am now at the configuration part where I want to tell EF to use the initializer class. My web.config file looks like this, not like the one in the tutorial (which was made using EF 6.1.0):
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<!--
Configure your application settings in appsettings.json. Learn more at http://go.microsoft.com/fwlink/?LinkId=786380
-->
<system.webServer>
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified"/>
</handlers>
<aspNetCore processPath="%LAUNCHER_PATH%" arguments="%LAUNCHER_ARGS%" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" forwardWindowsAuthToken="false"/>
</system.webServer>
</configuration>
From what I understand, for flexibility reasons, the configuration is now done in Startup.cs, but I cannot find info on how to use the DbContext I created and the Initialize class that I also created for seeding. Any ideas?
Cheers!

Cannot get caching for static recources (CSS, images) does to work in Azure Web App

I have an Azure account with a Web Application that is in the very early stages of development.
I am using Google Pagespeed Insights to test for any performance issues ( https://developers.google.com/speed/pagespeed/insights/ )
It tells me I don't have the cache set for my static resources. So I have enabled caching in the web.config file for my web application by adding the following code:
<system.webServer>
<staticContent>
<clientCache cacheControlCustom="public" cacheControlMaxAge="00.12:00:00" cacheControlMode="UseMaxAge" />
</staticContent>
</system.webServer>
Yet this does not work (I check the headers with Chrome Dev Tools).
Any ideas on what I am doing wrong?
Thank you.
Never mind, got it figured out.
Had to take out the following code out of web.config:
<handlers>
<add name="httpPlatformHandler" path="*" verb="*" modules="httpPlatformHandler" resourceType="Unspecified"/>
</handlers>
<httpPlatform processPath="%DNX_PATH%" arguments="%DNX_ARGS%" stdoutLogEnabled="false" startupTimeLimit="3600"/>
It was there from the ASP.NET 5 MVC project I set up earlier.

MVC WebAPI2 attribute routing using a path ending with a route parameter of type double

We are having an issue with WebApi2 attribute routing. We recently upgraded to MVC5 and Web Api 2. As part of the upgrade we shifted our Web Api to use Attribute routing.
One of our API calls allows for data to be requested using a latitude and longitude bounding box.
https://myapi.com/v1/things/area/{toplat}/{leftlon}/{botlat}/{rightlon}
This worked in the previous api, but not in the new one. We can't find a configuration that allows this to work. The final argument {rightlon} is a double and the xx.XXX is interpreted as a file extension.
Specifying the parameters as a double {toplat:double} had no impact. We can't easily force the legacy clients to update to include a trailing slash as some posts suggest. This config change also didn't work for us.
Why is my Web API method with double args not getting called?
Has anyone found a way to use attribute routing in WebApi2 to allow for a route that has a double/decimal/float as the last route parameter?
Solved.
The linked article did include the solution but also needed the correct format on the Attribute Routing.
[HttpGet] [Route("~/v1/things/area/{toplat:double}/{leftlon:double}/{botlat:double}/{rightlon:double}")]
in the web.config
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
<modules>
<remove name="UrlRoutingModule-4.0" />
<add name="UrlRoutingModule-4.0" type="System.Web.Routing.UrlRoutingModule" preCondition="" />
</modules>
</system.webServer>

Configure IISExpress 8 to use ASP.NET to handle requests for a .gif file?

I'm trying to get a custom image handler for .gif files working in an MVC website on my development machine which runs Visual Studio 2013. I'm basing it on an article by Scott Hanselman in which he dynamically generates a png.
I have a class which inherits from IHttpHandler and implements a ProcessRequest method (I don't think the code is relevant so I'm not including it). I've added an entry to the web.config like this:
<system.webServer>
<handlers>
<add name="ImageHandler" verb="*" path="*.gif" type="StaticContentWorkbench.Infrastructure.CustomGIFHandler" />
Unfortunately this isn't working so I did some research and found out that I probably need to alter the IIS configuration so that .gif files are handled by ASP.NET. I tried adding an entry to the system.webserver - handlers section of the IISExpress application.config file just before the last entry:
<add name="PageHandlerFactory-ISAPI-4.0_64bit_Add_Gifs" path="*.gif" verb="*" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
<add name="StaticFile" path="*" verb="*" modules="StaticFileModule,DefaultDocumentModule,DirectoryListingModule" resourceType="Either" requireAccess="Read" />
However this hasn't worked either and now I'm pretty much stuck.
How do I correctly configure IISExpress 8 to use ASP.NET to handle requests for a .gif file?
I had the same problem,
what worked for me was this
<system.webServer>
<handlers>
<add verb="GET,HEAD" name="DocHandler"
path="*.pdf"
type="Web.DocHandler" />
</handlers>
</system.webServer>
Problem is that you need to map every extension singularly, you cannot put multiple extension in the path property.
In your case, try to specify the verbs you need instead of *
Hope this helps

PUT + DELETE Http Verbs returning 401/405 from API on shared hosting webserver

I have created an MVC Web Api for some university coursework, that works as expected on my development machine (Running VS11).
However when I deploy the application to the webserver on 123reg HttpVerbs other than GET and POST appear to not reach my application at all, initially a 401 Not Authorised response was returned; however after turning off the "WebDAV" module as suggested here these 401s became 405 Method not allowed. In this case I only disabled the handlers as disabling both the handlers and the module meant that my application did not start at all (Error 500 without a stacktrace [custom errors are off]).
I am planning to utilise the forms membership provider to add authentication capabilities to my API, however I removed any [Authorise] attributes from my code when 401s began appearing.
Applications on 123Reg's shared hosting are run under Medium trust.
I have been in contact with 123Reg support, and they have been semi helpful, but have since decided that they cannot help me further (They suggested adding HttpHandlers as detailed below) (Apparently, I should consult a web designer...)
Things I have tried:
I have added [AllowAnonymous] Attributes to my controllers and/or actions with no effect.
I have added the authorization web.config attribute allowing all verbs and paths to all users both authenticated and not:
<authorization>
<allow users="*" />
<allow users="?" />
<allow verbs="*" users="*" />
<allow verbs="*" users="?" />
</authorization>
I have added (As suggested by 123Reg):
<system.webServer>
<handlers>
<remove name="WebDAV" />
<add name="PUTVerbHandler" path="*" verb="PUT" modules="ProtocolSupportModule" resourceType="Unspecified" />
<add name="DELETEVerbHandler" path="*" verb="DELETE" modules="ProtocolSupportModule" resourceType="Unspecified" />
</handlers>
</system.webServer>
This appeared to be a step forward, as we now receive 405 responses rather then 401 respones, however I am now unable to make any further progress. Additionally I have also added:
<httpHandlers>
<add verb="*" path="*" type="System.Web.Mvc.MvcHttpHandler"/>
</httpHandlers>
This also made no difference.
Any help you can give would be much appreciated (I dont really want to have to move host for this application!)
This post solved my problem. I did all the regular things: added all the necessary <handlers> entries, disabled WebDAV, but I still had 401.3 Unauthorized.
Enabling forms authentication solved the problem:
<system.web>
<compilation debug="true" targetFramework="4.0" />
<authentication mode="Forms" />
</system.web>
I found this: http://forums.iis.net/t/1163441.aspx
From the looks of that forum post, you need to completely uninstall WebDAV for the PUT and DELETE Verbs to work. This is not going to help on a shared webhosting scenario unfortunately.
For me it was something different.
I had to go to the site folder, open the security tab for the folder, press Edit button to change group or user names permissions, find the site from my IIS 8 sites and give it a full control permission.

Resources