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

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

Related

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>

OData v4 Function always returns 404

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Ă  :)

HttpClient Call to WebApi Service on IIS 7.5 - 404 Not Found

I am new to WebApi and we have a requirement to create\maintain a token issuing web service. A colleague of mine provided his solution (beta) which he has allowed me to use. If I run the web service from my dev environment (VS 2012) I am able to query it and get the token back from a web browser (Chrome). I then wrote a test app to use HttpClient to query the service and get the token. This works fine from the service hosted in my dev environment but if I try to query it when hosted in IIS using my little test app I get a '404 Not Found' exception. But what is puzzling me is if I connect to the web service hosted in IIS from chrome it works?
My controller method is as follows:
[HttpGet]
public IHttpActionResult GetToken(string username, string password, string realm)
{
return Json("TOKEN-STRING");
}
And my config:
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules runAllManagedModulesForAllRequests="true">
<remove name="UrlRoutingModule-4.0" />
<add name="UrlRoutingModule-4.0" type="System.Web.Routing.UrlRoutingModule" preCondition="" />
</modules>
<handlers>
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
<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" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,PUT,DELETE,DEBUG" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,PUT,DELETE,DEBUG" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
</handlers>
I have set my application pool to 'Integrated' within IIS.
My logic says to me that if I am able to retrieve the token from Chrome but not from my app, then there should be nothing wrong with IIS but rather a config\setting\programming error in my app.
Here is the little method I wrote to get the token:
async private void GetToken()
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost/TokenServer/");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = client.GetAsync("/api/TokenServer/GetToken/name/password/realm").Result;
string result = await response.Content.ReadAsStringAsync();
if (!response.IsSuccessStatusCode)
{
//Error handling
return;
}
//Extract token from response
JavaScriptSerializer json_serializer = new JavaScriptSerializer();
Token = DeserializeJsonToken(result);
}
I have read and tried many suggestions but none seem to work for me. I have been stuck with this for two days now and the deadline is creeping :)
Tx
The issue here is with the Url where you have a leading / which causes the TokenServer part of the baseaddress Url to be not considered. So modify the call like the following:
client.GetAsync("api/TokenServer/GetToken/name/password/realm").Result;
A tip: Tools like Fiddler can be of great use in situations like these. It helps in diagnosing the raw requests that are sent to the service.

DELETE/PUT verbs result in 404 Not Found in WebAPI, only when running locally

I know this is a commonly addressed issue, and I've done everything that many posts here on SO suggest. When I try to delete a record using WebAPI (version 2) from my MVC5 front end running under local IIS, I get a 404 Not Found response. Here are the things I've tried:
I've added the following under <system.webServer /> in my WebAPI web.config:
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules runAllManagedModulesForAllRequests="true">
<remove name="WebDAVModule" />
</modules>
<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>
I've followed the instructions at: http://geekswithblogs.net/michelotti/archive/2011/05/28/resolve-404-in-iis-express-for-put-and-delete-verbs.aspx, which basically say to modify the ExtensionlessUrlHandler-Integrated-4.0 in IIS "Handler Mappings". It says to double click on the handler, click "Request Restrictions", and "Allow PUT and DELETE verbs". I've done this, and I still get the 404 error.
I've done an IIS reset.
Here's my MVC5 front end code that calls the WebAPI delete method - please note that when I manually navigate to api/bulletinboard/get/{0} where {0} is an integer, I get a valid JSON response. Below, contactUri is http://localhost/SiteName/api/bulletinboard/get/53 which returns valid JSON:
[HttpPost, ActionName("Delete")]
public ActionResult Delete(string appId, int id)
{
response = client.GetAsync(string.Format("api/bulletinboard/get/{0}", id)).Result;
contactUri = response.RequestMessage.RequestUri;
response = client.DeleteAsync(contactUri).Result;
if (response.IsSuccessStatusCode)
{
return RedirectToAction("MessageList", new { appId = appId });
}
else
{
LoggerHelper.GetLogger().InsertError(new Exception(string.Format(
"Cannot delete message due to HTTP Response Status Code not being successful: {0}", response.StatusCode)));
return View("Problem");
}
}
Here's my WebAPI delete method:
[HttpDelete]
public HttpResponseMessage Delete(int id)
{
BulletinBoard bulletinBoard = db.BulletinBoards.Find(id);
if (bulletinBoard == null)
{
return Request.CreateResponse(HttpStatusCode.NotFound);
}
db.BulletinBoards.Remove(bulletinBoard);
try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException ex)
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
}
return Request.CreateResponse(HttpStatusCode.OK, bulletinBoard);
}
Here's my WebApiConfig.cs in my WebAPI project:
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
config.EnableCors();
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "ApiWithActionName",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
config.Formatters.Remove(config.Formatters.XmlFormatter);
config.Formatters.Add(new PlainTextFormatter());
}
QUESTION: What else can I try to resolve this error? This works fine when deployed from my local environment to my company's development servers.
for those who still looking for enable DELETE & PUT The below code solve my problem
<validation validateIntegratedModeConfiguration="false" />
<handlers>
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<!--This will enable all Web API verbose-->
<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" />
</handlers>
I've followed the instructions at: https://forums.asp.net/t/1961593.aspx?DELETE+PUT+verbs+result+in+404+Not+Found+in+WebAPI+only+when+running+locally
That says to only change this piece of code in your Web.config, and works fine for me!
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
</customHeaders>
</httpProtocol>
<validation validateIntegratedModeConfiguration="false" />
<handlers>
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<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" />
</handlers>
</system.webServer>
If you are using IIS, make sure you have the HTTP Verb set to allowed in Request Filtering. If its not there, you can set it to allow it on the side.
We were struggling with DELETE/PUT returning 404 errors on IIS 8. We did all of the above answers changing web.config to accept all Verbs, enabling put/delete in the request filtering. We had also disabled webDAV multiple ways. We found that the application pool was set to classic verses integrated (what it should have been). Now DELETE/PUT verbs work fine.
Mark Jensen solution worked for me.
Just changed my Application Pool from "Classic" to "Integrated" and my requests worked.
This issue can be fixed by IIS level configuration-
Open IIS->select your website->IIS (section) ->Request Filtering ->HHTP Verbs
Remove DELETE verb/ OR allow DELETE verb
Issue will get resolved.
What I did was just switch from using local IIS to IIS Express via the project properties on my WebAPI project, as a workaround. Doing this and deleting a record then resulted in a 405 Method Not Allowed error. I then changed the lines of code:
response = client.GetAsync(string.Format("api/bulletinboard/get/{0}", id)).Result;
contactUri = response.RequestMessage.RequestUri;
response = client.DeleteAsync(contactUri).Result;
To:
response = client.DeleteAsync(string.Format("api/bulletinboard/delete/{0}", id)).Result;
This is very strange because I have another project that runs the first block of code and it deletes records just fine. Anyways, this resolved my local problem. I understand this doesn't really resolve my main issue which was using local IIS, but this workaround worked for me.
If your project is working under IIS and not under IISExpress, try to set IISExpress Managed Pipeline Mode to Integrated.
PUT and DELETE verbs seems to have problem under Classic Managed Pipeline mode.
Good luck..
Roberto.
For me it was an ISAPI module called UrlScan which I had to completely remove from the application.

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