OData v4 Function always returns 404 - c#

Trying to move from OData v3 to OData v4. Why do I keep getting a 404 when trying to use OData Functions?
Web API Config:
ODataModelBuilder builder = new ODataConventionModelBuilder();
//etc
builder.EntitySet<LocalizableString>("LocalizableStringApi");
//etc
var getComparitiveTableFunction = builder.EntityType<LocalizableString>().Collection.Function("GetComparitiveTable");
getComparitiveTableFunction.Parameter<string>("cultureCode");
getComparitiveTableFunction.ReturnsCollection<ComparitiveLocalizableString>();
//etc
config.MapODataServiceRoute("OData_Kore_CMS", "odata/kore/cms", builder.GetEdmModel());
C# Code:
[EnableQuery(AllowedQueryOptions = AllowedQueryOptions.All)]
[HttpGet]
//[ODataRoute("Default.GetComparitiveTable(cultureCode={cultureCode})")] // Tried this, but gets errors and I noticed the function is in the OData model anyway without this, so should be fine.
public virtual IHttpActionResult GetComparitiveTable([FromODataUri] string cultureCode)
{
// Implementation
return Ok(query);
}
XML Returned from $metadata:
<Schema Namespace="Default">
<Function Name="GetComparitiveTable" IsBound="true">
<Parameter Name="bindingParameter" Type="Collection(Kore.Localization.Domain.LocalizableString)"/>
<Parameter Name="cultureCode" Type="Edm.String" Unicode="false"/>
<ReturnType Type="Collection(Kore.Localization.Models.ComparitiveLocalizableString)"/>
</Function>
...
As you can see, it's in the schema / OData model... yet the following query does not work:
http://localhost:30863/odata/kore/cms/LocalizableStringApi/Default.GetComparitiveTable(cultureCode='en-US')
I have also tried the following:
http://localhost:30863/odata/kore/cms/LocalizableStringApi/GetComparitiveTable(cultureCode='en-US')
http://localhost:30863/odata/kore/cms/Default.GetComparitiveTable(cultureCode='en-US')
http://localhost:30863/odata/kore/cms/GetComparitiveTable(cultureCode='en-US')
All of the above result in a 404.
So... what am I doing wrong here?

I solve a similar problem adding a trailing slash to the requested url.

I solved this by adding the following line in my web.config, under <system.webServer>:
<modules runAllManagedModulesForAllRequests="true">
This may cause performance issues though, if I remember correctly. So it's not ideal. Any better solutions are very welcome...

You need a module that goes by the name of UrlRoutingModule-4.0 to be running through IIS. This solution causes all your registered HTTP modules to run on every request, not just managed requests (e.g. .aspx). This means modules will run on ever .jpg .gif .css .html .pdf etc.
So, a better solution would be to add the following in your web.config
<modules>
<remove name="UrlRoutingModule-4.0" />
<add name="UrlRoutingModule-4.0" type="System.Web.Routing.UrlRoutingModule" preCondition="" />
</modules>
Source: http://www.britishdeveloper.co.uk/2010/06/dont-use-modules-runallmanagedmodulesfo.html

This is a solution to prevent 404 Not Found error with OData functions / actions.
Benefits of this solution
Works with OData URI without slash at end (example: http://domain.org/odata/Objects/ObjectService.Action)
Works with OData URI with a slash at end (example: http://domain.org/odata/Objects/ObjectService.Action/)
Doesn't cause any performance issue.
Add theses lines in your web.config
<system.webServer>
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
<add name="ExtensionlessUrlHandler-Integrated-4.0Custom" path="/odata*" verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
Et VoilĂ  :)

Related

How to protect or secured ASP.NET MVC from XSS?

I'm creating a web application using the latest version of ASP.NET MVC 5.2.3. I just concern in XSS attack. I figure out in ASP.NET Core is perfectly working protecting from this attack the XSS and this framework totally amazing but it lacked third party I need to my project. Here's my concern. I already enabled the custom error too but I disabled it currently for testing.
But I want to make sure this will catch also.
Input Validation is passed. To avoid this exception or error.
A potentially dangerous Request.Form value was detected from the client (Name="").
using, the [AllowHtml] attribute this is fine or using the AntiXss library.
But, from the URL. Example URLs,
http://localhost:54642/Employees/
http://localhost:54642/Employees/?a=<script>
link or url
this error should like,
A potentially dangerous Request.Path value was detected from the client (<).
So my solution is enabling this from Web.config then it works!
But Troy Hunt said from his tutorial this is not a good or better practice for this error. So I decided to look the best solution from this XSS attack.
In my form I normally add this anti-forgery token
#Html.AntiForgeryToken()
then on my controller I made sure validate the token
[ValidateAntiForgeryToken]
also when passing the variable or data, I always declare correct variable. Anyways if its member area page you can always restrict access to correct member roles example like
[Authorize] // for registered user
or more filtered
[Authorize(Roles = "SUBSCRIBER.VIEW")]
Below is only applicable for .net 4.5 and above
// web.config
<system.Web>
<httpRuntime targetFramework="4.5" />
</system.Web>
// enabling anti-xss
<httpRuntime targetFramework="4.5" encoderType="System.Web.Security.AntiXss.AntiXssEncoder,System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
Request validation Lazy validation was introduced in ASP.NET 4.5, I
just did some testing on it and it seems that lazy validation is the
enabled regardless of how you set the "requestValidationMode", after
you've installed the 4.5 framework.
Check out OWASP site. Here is the common ones I add in system.web in web.config file of a webapi app.
<httpProtocol>
<customHeaders>
<remove name="Server" />
<remove name="X-Powered-By" />
<remove name="X-Frame-Options" />
<remove name="X-XSS-Protection" />
<remove name="X-Content-Type-Options" />
<remove name="Cache-Control" />
<remove name="Pragma" />
<remove name="Expires" />
<remove name="Content-Security-Policy"/>
<clear />
<add name="X-Frame-Options" value="DENY" />
<add name="X-XSS-Protection" value="1; mode=block"/>
<add name="X-Content-Type-Options" value="nosniff" />
<add name="Cache-Control" value="no-cache, no-store" />
<add name="Pragma" value="no-cache" />
<add name="Expires" value="Sun, 1 Jan 2017 00:00:00 UTC" />
<add name="Content-Security-Policy" value="default-src 'self' 'unsafe-inline' data; img-src https://*;"/>
</customHeaders>
</httpProtocol>

Getting PUT and DELETE verbs in WebAPI2 to work on IIS 8.5

I am attempting to publish code to my company test web server and I'm getting a multitude of errors returned from IIS when attempting to call any methods using the PUT or DELETE verb. I've researched this particular issue, and all of the results that I've attempted either do nothing, or generate a new error. When I try with the default system.webServer configuration I receive the general 405 method not allowed error, here's that portion of 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>
</system.webServer>
From digging through Google and several stack articles, the majority of accepted answer specify to remove WebDAV through the web config file, which I've done, and here's that updated code:
<system.webServer>
<modules>
<remove name="WebDAVModule" />
</modules
<validation validateIntegratedModeConfiguration="false" />
<handlers>
<remove name="WebDAV" />
<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>
</system.webServer>
When I try using just removing the WebDAV handler, I continue to get the 405 method not allowed error, but as soon as I remove the WebDAVModule, my error becomes a 500 Internal Server Error, and viewing from the server doesn't actually give me any further information.
I've also attempted suggestions revolving around removing and adding the "ExtensionlessUrlHandler-ISAPI-4.0_32bit" & "ExtensionlessUrlHandler-ISAPI-4.0_64bit" handlers, with the same results (405 when don't remove the WebDAVModule or 500 when I do remove it).
Here's the methods on my WebApi controller that I'm attempting to call, maybe this is the problem, though it works just fine in my development environment:
public string PutRegistrationBatch(RegistrationBatch Model) {
// Code to save the model to our database
}
public string DeleteRegistrationBatch(RegistrationBatch Model) {
// Code to delete the item from the database
}
UPDATE
I ran a trace on the application and I'm seeing GET and POST commands get through to the site, however none of the PUT or DELETE commands get through to the site:
1/10/2017 1:22:41 PM /api/RegistrationBatch/ 200 GET
1/10/2017 1:22:55 PM /api/RegistrationBatch/ 200 POST
It seems as though the PUT and DELETE commands are being filtered out and refused at the host level and never making into my application.
UPDATE
It seems that WebDAV is the underlying issue, but we run a web service that utilizes this technology, so removing it is not an option until we can update that service. In the mean time, I've found that a work around outlined by Scott Hanselman here (http://www.hanselman.com/blog/HTTPPUTOrDELETENotAllowedUseXHTTPMethodOverrideForYourRESTServiceWithASPNETWebAPI.aspx) allows for me to send PUT and DELETE requests as a POST request.
I wouldn't suggest that is is an answer to the problem, but it at least allows me to work around the problem until such a time as we can uninstall WebDAV and hopefully that will allow my Web Api 2 application(s) to work properly.
You need to apply the [HttpPut] and [HttpDelete] attributes on the respective actions
[HttpPut]
public string PutRegistrationBatch(RegistrationBatch Model) { ... }
[HttpDelete]
public string DeleteRegistrationBatch(RegistrationBatch Model) { ... }
And in the config file you should also try to use the specific verbs you want to allow
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
If you have the WebDAV IIS feature installed, it can cause conflicts with Put, Delete, and Patch requests (maybe more... can't remember). You can either uninstall the feature server-wide or manually remove the HttpModule and HttpHandlers from the system.webServer element to target this specific application. See https://stackoverflow.com/a/26003440/179223
I remember getting into similar ditch sometime ago. Eventually this worked for me.
Reset all module configurations of 'Default Web Site' and your website to default values in IIS. You can do this by
1. Select your website, double click "Modules"
2. Click on "Revert to Parent" link under Actions panel on right side
Use the following into your Web.config
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" runManagedModulesForWebDavRequests="true">
<remove name="WebDAVModule" />
</modules>
<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>
</system.webServer>

Some of my asp.net api attribute based routing are returning 404 (not found)

In the asp.net mvc 5 + web api 2 am working on, some of the webapi routes that I defined are not working, while some are working perfectly. I can't seem to identify what the problem is. And before you ask I have read the whole SO questions and applied all the solutions I can find, but none of it seems to work in my current situation. I also checked, double checked and yet I can't figure out why. Here are some of the configurations and route registrations that I think affects web api.
Route definition
[HttpPost]
[Route("FollowApi/{profileId:int}/FollowClient" Name = "FollowClient")]
Application_start configuration
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
Webconfig configuration
<system.webServer>
<modules>
<remove name="FormsAuthentication" />
<add name="ImageResizingModule" type="ImageResizer.InterceptModule" />
<remove name="UrlRoutingModule-4.0" />
<add name="UrlRoutingModule-4.0" type="System.Web.Routing.UrlRoutingModule" preCondition="" />
</modules>
<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>
</system.webServer>
Please, any help or pointers as to why this problem is occurring will be seriously appreciated as I am in a time constrained situation.
Edit
Working api
public class CommonApiController : BaseApiController
{
[Authorize]
[HttpGet]
[Route("Client/GetInfoCounts")]
public IHttpActionResult GetInfoCounts()
{
//Method body
}
}
Not working api
public class FollowApiController : BaseApiController
{
[HttpPost]
[Route("FollowApi/{profileId:int}/FollowClient")]
public IHttpActionResult Follow(int profileId)
{
//Method body
}
}
It looks like the RoutePrefix on the controller was not included in the client call. My take away from this is that it makes sense to have a certain pattern for troubleshooting these kind of problems.
Something like:
Is the url correct?
Is the httpMethod correct?
Are the parameters named correctly?

ASP.NET MVC - Routing - an action with file extension

is there a way to achieve calling URL http://mywebsite/myarea/mycontroller/myaction.xml
This would basically "fake" requesting a file but the result would be an action operation that would serve a file created dynamically?
I tried this:
context.MapRoute(
"Xml_filename",
"Xml/{controller}/{action}.xml"
);
but whenever there is a filextension in the URL the routing fails and behaves as I was requesting a file directly.
I suspect this might be because of using extension less url handler.
<add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
Thank you for any suggestions.
Jakub
You need to map requests for your XML files to TransferRequestHandler in web.config. Otherwise IIS will handle the request.
Jon Galloway explains how to do this here.
In summary, you add this element to location/system.webServer/handlers in your web.config:
<add name="XmlFileHandler" path="*.xml" verb="GET" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
The problem is that IIS will handle the .xml file as a static file and will by default not route the XML file through your MVC application. IIS handles the request and your MVC code never gets a change to route to this file.
There are a few ways around this.
I've found the easiest way to handle this by using the IIS Rewrite module to rewrite the URL from static file URL(s) to an MVC route:
<system.webServer>
<rewrite>
<rules>
<rule name="Live Writer Manifest">
<match url="*.xml"/>
<action type="Rewrite" url="route/xmlfilehandler"/>
</rule>
</rules>
</rewrite>
</system.webServer>
Make sure you have the IIS Rewrite Module installed (separate install from the Platform Installer). If you already are using the Rewrite handler this is the most efficient solution.
As pointed out above by Ben Foster and Jon Galloway's post, you can also map the TransferRequestHandler at your specific path you want to route. For compactness here's what you need to add to your web.config:
<system.webServer>
<handlers>
<add name="Windows Live Writer Xml File Handler"
path="wlwmanfest.xml"
verb="GET" type="System.Web.Handlers.TransferRequestHandler"
preCondition="integratedMode,runtimeVersionv4.0" responseBufferLimit="0"
/>
</handlers>
</system.webServer>
You can then use an Attribute Route to handle .xml file Urls. For example:
[Route("blog/wlwmanifest.xml")]
public ActionResult LiveWriterManifest() {... }
More info in this blog post:
http://weblog.west-wind.com/posts/2015/Nov/13/Serving-URLs-with-File-Extensions-in-an-ASPNET-MVC-Application
If you drop your xml file in one of the folders inside your website.
Try something like this:
C# - How to make a HTTP call

Dot character '.' in MVC Web API 2 for request such as api/people/STAFF.45287

The URL I'm trying to let work is one in the style of: http://somedomain.com/api/people/staff.33311 (just like sites as LAST.FM allow all sort of signs in their RESTFul & WebPage urls, for example "http://www.last.fm/artist/psy'aviah" is a valid url for LAST.FM).
What works are following scenarios:
- http://somedomain.com/api/people/ - which returns all people
- http://somedomain.com/api/people/staff33311 - would work as well, but it's not what I'm after
I'd want the url to accept a "dot", like the example below
- http://somedomain.com/api/people/staff.33311 - but this gives me a
HTTP Error 404.0 - Not Found
The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.
I've set up following things:
The controller "PeopleController"
public IEnumerable<Person> GetAllPeople()
{
return _people;
}
public IHttpActionResult GetPerson(string id)
{
var person = _people.FirstOrDefault(p => p.Id.ToLower().Equals(id.ToLower()));
if (person == null)
return NotFound();
return Ok(person);
}
The WebApiConfig.cs
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
I already tried following all the tips of this blogpost http://www.hanselman.com/blog/ExperimentsInWackinessAllowingPercentsAnglebracketsAndOtherNaughtyThingsInTheASPNETIISRequestURL.aspx but it still won't work.. I also think it's quite tedious and I wonder if there isn't another, better and more secure way.
We have our Id's internally like this, so we're going to have to find a solution to fit the dot in one way or another, preferably in the style of "." but I'm open to alternative suggestions for urls if need be...
Suffix the URL with a slash e.g. http://somedomain.com/api/people/staff.33311/ instead of http://somedomain.com/api/people/staff.33311.
Following setting in your web.config file should fix your issue:
<configuration>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
I've found that adding the following before the standard ExtensionlessUrlHandler solves the issue for me:
<add name="ExtensionlessUrlHandler-Integrated-4.0-ForApi"
path="api/*"
verb="*"
type="System.Web.Handlers.TransferRequestHandler"
preCondition="integratedMode,runtimeVersionv4.0" />
I don't think the name actually matters all that much except it probably helps if your IDE (Visual Studio in my case) is managing your site configuration.
H/T to https://stackoverflow.com/a/15802305/264628
I don't know what I am doing really, but after playing with the previous answer a bit I came up with another, perhaps more appropriate, solution:
<system.webServer>
<modules>
<remove name="UrlRoutingModule-4.0" />
<add name="UrlRoutingModule-4.0" type="System.Web.Routing.UrlRoutingModule" />
</modules>
</system.webServer>
I found that I needed to do more than just set the runAllManagedModulesForAllRequests attribute to true. I also had to ensure that the extensionless URL handler was configured to look at all paths. In addition, there is one more bonus configuration setting you can add which will help in some cases. Here is my working Web.config:
<system.web>
<httpRuntime relaxedUrlToFileSystemMapping="true" />
</system.web>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
<handlers>
<remove name="WebDAV" />
<remove name="OPTIONSVerbHandler" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*" verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
Note, specifically, that the ExtensionlessUrlHandler-Integrated-4.0 has its path attribute set to * as opposed to *. (for instance).
I'd use this in Web.config file:
<add name="ManagedSpecialNames" path="api/people/*" verb="GET" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
before standard "ExtensionlessUrlHandler".
For instance in my case I put it here:
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ManagedFiles" path="api/people/*" verb="GET" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
So you force URLs of such pattern to be managed by you, instead of standard management as files in application directory tree.
I got stuck in this situation but appending /
at the end of URL wasn't look clean for me.
so just add below in web.config handlers tag
and you will be good to go.
<add name="Nancy" path="api" verb="*" type="Nancy.Hosting.Aspnet.NancyHttpRequestHandler" allowPathInfo="true" />
I found that both way works for me: either setting runAllManagedModulesForAllRequests to true or add ExtentionlessUrlHandler as following. Finally i choose to add extensionUrLHandler since runAllManagedModulesForAllRequests do have performance impact to the site.
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<remove name="WebDAV" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*" verb="*"
type="System.Web.Handlers.TransferRequestHandler"
preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
I also faced this issue. I was under a circumstance where I was not supposed to play with IIS and website config related settings. So I had to make it working by making changes at the code level only.
The point is that the most common case where you would end up having dot character in the URL is when you get some input from the user and pass it as a query string or url fragment to pass some argument to the parameters in the action method of your controller.
public class GetuserdetailsbyuseridController : ApiController
{
string getuserdetailsbyuserid(string userId)
{
//some code to get user details
}
}
Have a look at below URL where user enters his user id to get his personal details:
http://mywebsite:8080/getuserdetailsbyuserid/foo.bar
Since you have to fetch some data from the server we use http GET verb. While using GET calls any input parameters can be passed only in the URL fragments.
So to solve my problem I changed the http verb of my action to POST. Http POST verb has the facility of passing any user or non-user input in body also. So I created a JSON data and passed it into the body of the http POST request:
{
"userid" : "foo.bar"
}
Change your method definition as below:
public class GetuserdetailsbyuseridController : ApiController
{
[Post]
string getuserdetailsbyuserid([FromBody] string userId)
{
//some code to get user details
}
}
Note: More on when to use GET verb and when to use POST verb here.

Categories