WebAPI Delete not working - 405 Method Not Allowed - asp.net-mvc

I appreciate any help on this as the site is supposed to go live tonight!
I have a web api controller with a Delete method. The method executes fine on my local machine running IIS Express (Windows 8) but as soon as I deployed it to the live IIS server (Windows Server 2008 R2) it stopped working and throws the following error message:
HTTP Error 405.0 - Method Not Allowed
The page you are looking for cannot be displayed because an invalid method (HTTP Verb) is being used
I have looked around the web for solutions and I implemented most reasonable ones. My web config has the following settings:
<system.webServer>
<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>
I have also tried to change the Handler Mappings and Request Filtering in IIS to no avail. Please note that the WebDAV Authoring Rules in IIS seems to be disabled.
Any ideas will be greatly appreciated
Thanks.

I found the solution eventually!
If you come across the same issue, add the following to your web.config
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules runAllManagedModulesForAllRequests="true">
<remove name="WebDAVModule"/> <!-- ADD THIS -->
</modules>
... rest of settings here

In some cases removing it just from modules can produce next error:
500.21 Handler "WebDAV" has a bad module "WebDAVModule" in its module list
Module: IIS Web Core Notification: ExecuteRequestHandler"
solution was suggested here. Also need to remove it from handlers.
<system.webServer>
<modules>
<remove name="WebDAVModule" />
</modules>
<handlers>
<remove name="WebDAV" />
</handlers>
</system.webServer>

In my case none of the above solutions worked. This was because I had changed the name of the parameter in my Delete method.
I had
public void Delete(string Questionid)
instead of
public void Delete(string id)
I need to use the id name because that's the name that is declared in my WebApiConfig file. Note the id name in the third and fourth lines:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
I got this solution from here.

The Javascript for HTTP DELETE verb must be like this:
$.ajax({
**url: "/api/SomeController/" + id,**
type: "DELETE",
dataType: "json",
success: function(data, statusText) {
alert(data);
},
error: function(request, textStatus, error) {
alert(error);
debugger;
}
});
Do not use something like this:
...
data: {id:id}
...
as when you use the POST method.

If you are using IIS 7.0 or later version.
This issue is mainly related to WebDAV extension module on IIS server.
this happened while Using Post OR delete action.
Please try below setting in web config
<system.webServer>
<modules>
<remove name="WebDAVModule" />
</modules>
<handlers>
<remove name="WebDAV" />
</handlers>
</system.webServer>

After trying almost every solutions here this worked for me.
Add this in your APIs config file
<system.webServer>
<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>
<modules>
<remove name="WebDAVModule" />
</modules>
</system.webServer>

I also had the same problem, I am calling WebAPi and is getting this error.
Adding following configuration in web.config for services solved my problem
<modules runAllManagedModulesForAllRequests="true">
<remove name="WebDAVModule"/> <!-- add this -->
</modules>
in web.config file solved my problem.
This is How i was calling from client side
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(environment.ServiceUrl);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.DeleteAsync("api/Producer/" + _nopProducerId).Result;
if (response.IsSuccessStatusCode)
{
string strResult = response.Content.ReadAsAsync<string>().Result;
}
}

Go to applicationHost.config (usually under C:\Windows\System32\inetsrv\config) file and comment out the following line in applicationHost.config
1)Under <handlers>:
<add name="WebDAV" path="*" verb="PROPFIND,PROPPATCH,MKCOL,PUT,COPY,DELETE,MOVE,LOCK,UNLOCK" modules="WebDAVModule" resourceType="Unspecified" requireAccess="None" />
2)Also comment out the following module being referred by the above handler under <modules>
<add name="WebDAVModule" />

In my case, I missed to add {id} to the [Route("")] and I got the same error.
Adding that fixed the problem for me: [Route("{id}")]

I had 405 error Method Not Allowed because I had omitted to make the Delete method on the WebApi controller public.
It took me a long time to find this (too long!) because I would have expected a Not Found error in this case, so I was incorrectly assuming that my Delete method was being denied.
The reason for Not Allowed rather than Not Found is that I also had a Get method for the same route (which will be the normal case when implementing REST). The public Get function is matched by the routing and then denied because of the wrong http method.
A simple error I know but it may save someone else some time.

Just to add. If this is your config
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
please keep doing as Hugo said, and do not set Route attribute to the controller get method, this gave a problem in my case.

I had the similar issue but for PUT - none of the other suggestions worked for me.
However i was using int rather than the default string for the id. adding {id:int} to the route solved my problem.
[Route("api/Project/{id:int}")]
public async Task<IHttpActionResult> Put(int id, [FromBody]EditProjectCommand value)
{
...
}

I am working on .Net 5 Api project, and adding :
<modules>
<remove name="WebDAVModule" />
</modules>
to the <system.webServer> part of web.config and
<handlers>
<remove name="WebDAV" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,PUT,DELETE,DEBUG" type="System.Web.Handlers.TransferRequestHandler" resourceType="Unspecified" requireAccess="Script" preCondition="integratedMode,runtimeVersionv4.0" responseBufferLimit="0" />
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
</handlers>
fixed it for me.
However, tricky part was making this work in the Azure DevOps CI-CD pipelines.
I managed to do it, and spoke about how I did it here:
Azure DevOps Release Pipeline Web.Config Edit

We had to add custom headers to our web.config as our request had multiple headers that confused the API response.
<httpProtocol>
<customHeaders>
<remove name="Access-Control-Allow-Methods" />
<remove name="Access-Control-Allow-Origin" />
<remove name="Access-Control-Allow-Headers" />
</customHeaders>
</httpProtocol>

[HttpPost] attribute on the top of Delete method solved this issue for me:
[HttpPost]
public void Delete(int Id)
{
//Delete logic
}

Related

Server Error in '/' Application. The resource cannot be found.

I am using nopCommerce 3.8 and I have an issue for some products
http://snknop.cloud.rt.ru/com3
http://snknop.cloud.rt.ru/com6
Those products exist in DB and I have Url records for those products.
Also it looks like urls with prefix comX don't go to web app. So I think this issue takes place before app. Probably some handlers remove access to comX urls.
For example:
http://snknop.cloud.rt.ru/com7 - I have Server error
http://snknop.cloud.rt.ru/com77- I have 404 error. This url handles by app.
com7 and com77 don't exist in UrlRecords
we are using standard nopCommerce configuration for handlers in web.config
<handlers>
<add name="SitemapXml" path="sitemap.xml" verb="*" type="System.Web.Routing.UrlRoutingModule" resourceType="Unspecified" preCondition="integratedMode" />
<add name="RobotsTxt" path="robots.txt" verb="*" type="System.Web.Routing.UrlRoutingModule" resourceType="Unspecified" preCondition="integratedMode" />
<add name="MiniProfiler" path="mini-profiler-resources/*" verb="*" type="System.Web.Routing.UrlRoutingModule" resourceType="Unspecified" preCondition="integratedMode" />
<add name="DenyAccessToPluginDLLs" verb="*" path="*.dll" type="System.Web.HttpForbiddenHandler" />
<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>
any ideas?
Please let me know if you need anything else. Thank you in advance.
Are you sure this is the correct URL of the product? You can check the correct product URL in the NopCommerce Admin menu.
Go to http://snknop.cloud.rt.ru/Admin/Product/List and choose the product that you can't find. Then click on the 'Edit' button. In the edit page, on the top-right, click on the purple 'Preview' button. It will open a new window with the correct URL of your product.
If there is an error during the preview, go to http://snknop.cloud.rt.ru/Admin/Log/List. You should have all the information about the error there.

GET and POST working but DELETE not on IIS 8.5 Server

I am making delete requests from an AngularJS app to an asp.net web api and I am getting below error -
XMLHttpRequest cannot load http://api.prod.com/api/v1/proddetails/34. No
'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost:5100' is therefore not allowed access. The response
had HTTP status code 403.
Method:
[HttpDelete]
public HttpResponseMessage Delete(int id)
Web Config:
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules runAllManagedModulesForAllRequests="true">
<add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah" preCondition="managedHandler" />
<add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah" preCondition="managedHandler" />
<add name="ErrorFilter" type="Elmah.ErrorFilterModule, Elmah" preCondition="managedHandler" />
<remove name="WebDAVModule" />
</modules>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="12582912" />
<!--12 MB-->
</requestFiltering>
</security>
<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>
</system.webServer>
Please help.
Note: The machine is a Windows Server 2012 R2 running IIS 8.5 on AWS EC2. I have CORS setup properly like this on the controller -
[EnableCors(origins: "*", headers: "*", methods: "*")]
Edit1:
I was looking at my applicationHost.config file, and it has these lines -
<add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG" modules="IsapiModule" scriptProcessor="C:\windows\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" modules="IsapiModule" scriptProcessor="C:\windows\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" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
But there are so many of them, and none of them have DELETE as allowed verb. Can this be causing an issue?
Edit2:
As requested, this is the AngularJS request code -
$http.delete('http://api.prod.com/api/v1/proddetails/' + data)
.success(function (data, status, headers, config) {
console.log(data);
if(data.status == "200")
{
console.log('data deleted');
}
deferred.resolve(data);
})
.error(function (data, status, headers, config) {
console.log("some error occurred");
deferred.reject(data);
});
Try changing this property of Web.config:
<add name="ExtensionlessUrl-Integrated-4.0"
path="*."
verb="GET,HEAD,POST,DEBUG,DELETE,PUT"
type="System.Web.Handlers.TransferRequestHandler"
preCondition="integratedMode,runtimeVersionv4.0" />
Two things could be going on here.
First
In IIS if you click at the root most node (computer name), you can see under management in the right frame an icon called Feature Delegation. Open that by double clicking it. From within there, you will see a list of delegations, find Handler Mappings and make sure it is set to read/write. This will allow the site to override the default handlers that may not be allowing the DELETE verb. Then make sure the web.config reflects the verbs you want to be enabled for extensionlessurlhandler.
Second
You must implement the options verb on your API controllers like this:
[HttpOptions, AllowAnonymous]
public IHttpActionResult Options()
{
return StatusCode(HttpStatusCode.OK);
}
this is because CORS will "pre-flight" many requests that are not a simple get or post.
from the mozilla docs on the subject:
Preflighted requests
Unlike simple requests (discussed above), "preflighted" requests first
send an HTTP request by the OPTIONS method to the resource on the
other domain, in order to determine whether the actual request is safe
to send. Cross-site requests are preflighted like this since they may
have implications to user data. In particular, a request is
preflighted if:
It uses methods other than GET, HEAD or POST. Also, if POST is used to
send request data with a Content-Type other than
application/x-www-form-urlencoded, multipart/form-data, or text/plain,
e.g. if the POST request sends an XML payload to the server using
application/xml or text/xml, then the request is preflighted.
It sets custom headers in the request (e.g. the request uses a header
such as X-PINGOTHER)
Also, localhost may have issues with CORS. There are workarounds to develop with, see:
Deadly CORS when http://localhost is the origin
Change the following tag in your applicationHost.config file:
<add name="ExtensionlessUrlHandler-Integrated-4.0"
path="*."
verb="GET,HEAD,POST,DEBUG, DELETE"
type="System.Web.Handlers.TransferRequestHandler"
preCondition="integratedMode,runtimeVersionv4.0"
responseBufferLimit="0" />

IIS hijacks CORS Preflight OPTIONS request

I am making a CORS POST request and setting the Content-Type header to json. This triggers a Preflight OPTIONS request to fire (this is good and expected)
This OPTIONS request is responded to with a 200 OK but this isn't coming from my WebAPI application.
I have a custom Message Handler in place and it never get's hit so the request is getting responded to by IIS prior to hitting ASP.NET it seems.
I have found several posts on the subject and they say the following
Make sure WebDav is uninstalled / removed / disabled - DONE
Make sure the OPTIONSVerbHandler is removed / changed to use aspnet_isapi.dll - TRIED BOTH
Make sure the extensionlessURLHandler includes the OPTIONS verb - DONE
However, my options request is still getting hijacked. By that I mean, IIS responds with at 200 OK but isn't including an Access-Control-Allow-Origin header in the response. It isn't including this header because it is never getting to my WebAPI CORS code that would set this header.
The two best posts I could find that sound like my issue are
here: JQuery stuck at CORS preflight and IIS ghost response
and here: http://brockallen.com/2012/10/18/cors-iis-and-webdav/
I have tried turning on Failed Request tracing (FERB) in IIS and set it to trace all 200 status codes. I don't ever see the options request being logged... Not sure if this means FERB doesn't track OPTIONS requests or if I need to change something in the FERB settings to make it track OPTIONS requests, Or if this is a clue to what my problem is?
This is ASP.NET WebAPI 2.0 running on IIS 7.5 (Also tested on IIS 8 and IISExpress with same results)
Doesn't matter what browser (Chrome, FF, and IE all fail the same way)
I have tried everything I can find on the subject and still can't fix my problem.
Help me StackOverflow, you're my only hope.
A couple of things you can try here, all web.config related, firstly modify your modules element to include the attribute runAllManagedModulesForAllRequests="true", as below:
<modules runAllManagedModulesForAllRequests="true">
<remove name="WebDavModule" />
</modules>
Then set your handlers to the below:
<handlers>
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="WebDav" />
<remove name="OPTIONSVerbHandler" />
<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>
This should do the trick, but if it doesn't, as a last resort you can force IIS to output the correct headers with the below:
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="GET,PUT,POST,DELETE,OPTIONS" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
</customHeaders>
</httpProtocol>
</system.webServer>
Be wary of the wildcard value, you should really set this to the domain name that your site will be hosted on.
that's what worked for me after 4 hours of searching/experimenting:
<handlers>
<remove name="OPTIONSVerbHandler" />
<add name="OPTIONSVerbHandler" path="*" verb="OPTIONS" modules="IsapiModule" scriptProcessor="C:\Windows\System32\inetsrv\asp.dll" resourceType="Unspecified" requireAccess="None" />
</handlers>
I tried all of the above suggestions as well as others I found on SO and what mattered in my situation was we had Request Filtering enabled on IIS and the OPTIONS HTTP Verb was not in the list of allowed verbs. Once I added it I was able to sort out the rest of it.
I had the same issue and the following web.config settings fixed it for me.
<modules runAllManagedModulesForAllRequests="false">
<remove name="FormsAuthenticationModule" />
</modules>
<handlers>
<remove name="OPTIONSVerbHandler" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
I was then able to handle CORS OPTIONS requests manually in Application_BeginRequest.
I was originally using the library detailed in this blog post for handling CORS requests. The product I'm working on requires that runAllManagedModulesForAllRequests be set to false, though. This is why I had to set up a custom implementation, but if you don't have that requirement you should give that library a try. It worked great when I was able to have runAllManagedModulesForAllRequests set to true.
In our case it was request filtering in IIS disabling OPTIONS verb at the root web application level. Open up IIS Manager, click on root application, click on Request Filtering, if OPTIONS appears in list either remove or Allow Verb. Wish I had checked this first as lots of wasted time.
In my case, I missed the Microsoft.WebApi.Cors package.
Installed this package and configured it like so in the WebApiConfig class:
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.EnableCors(new EnableCorsAttribute("*","*","*"));
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
Please fine-tune this before using in production because you probably don't want to have wild-cards for everything
This is what worked for me:
<system.webServer>
<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>
Check if URLScan tool is installed on IIS.
When so check following section:
;
; The verbs (aka HTTP methods) listed here are those commonly
; processed by a typical IIS server.
;
; Note that these entries are effective if "UseAllowVerbs=1"
; is set in the [Options] section above.
;
GET
HEAD
POST
OPTIONS
I know this is an old post, but I just went through the exact same problem.
In my situation, I have CORS installed for both OWIN and WebAPI. The OWIN CORS middleware was intercepting the OPTIONS call long before it ever made it to the WebAPI stuff. Maybe this well help someone else in the future.
I have installed Microsoft.AspNet.WebApi.Cors & Microsoft.Owin.Cors for my oWin based WebAPI and added app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll); at config like below:
public class Startup : IStartup, IAppStartup
{
public void Configuration(IAppBuilder app)
{
var config = this.GetInjectionConfiguration();
BootstrapperWebApi bootstrapperWebApi = (BootstrapperWebApi)this.GetBootstrapperWebApi(config);
bootstrapperWebApi.Initialize(true)
.EnableLogging()
.DisableWebApiDefaultExceptionHandler();
WebApiConfig.Register(config);
app.UseOwinExceptionHandler();
app.Use<LoggerMiddleware>();
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
//others stuff
}
I tried all the mentioned posts but nothing worked for me, then i shifted my ASP.Net Web API 2 service to windows server 2012 (IIS 8.5) and same service worked without any changes. So issue was specific to IIS 7.5 on windows 7 machine.
In my case I did this:
<verbs allowUnlisted="true" applyToWebDAV="true">
<remove verb="OPTIONS"/>
<add verb="OPTIONS" allowed="true"/>
</verbs>
</requestFiltering>
</security>
When I added <add verb="OPTIONS" allowed="true"/> to the web.config, the application failed to start with this error
HTTP Error 500.19 - Internal Server Error
The requested page cannot be accessed because the related configuration data for the page is invalid.
Cannot add duplicate collection entry of type 'add' with unique key attribute 'verb' set to 'OPTIONS'
So I had to remove it first.
I have the same issue. The OPTIONS request return 200 OK status but it does not contain Access-Control-Allow-Origin header. The problem was our customer network policy blocking the OPTIONS verb request and response the warning message with 200 OK status. I know this is the old post but I want to share my case for anyone needed.
One more case, maybe it will save time for somebody. When I used config with HttpConfiguration.EnableCors all was working fine but when I used web.config file it was failing with CORS errors. It started work after I removed the .vs folder.
<figure>
<img src="https://i.stack.imgur.com/CbRyM.png" alt="">
<figcaption> change the OptionsVerbHangle</figcaption>
</figure>
<figure>
<img src="https://i.stack.imgur.com/wjcMV.png" alt="Minha Figura">
<figcaption>Adicione * and in the case of php use fastcgimodule</figcaption>
</figure>
<figure>
<img src="https://i.stack.imgur.com/wRwpi.png" alt="Minha Figura">
<figcaption>Mapping to folder
</figcaption>
</figure>
<figure>
<img src="https://i.stack.imgur.com/hhqJi.png" alt="Minha Figura">
<figcaption>all verbs
</figcaption>
</figure>
<figure>
<img src="https://i.stack.imgur.com/86kKX.png" alt="Minha Figura">
<figcaption>Select script
</figcaption>
</figure>
Just follow the images below to unlock the colors in IIS
enter image description here
enter image description here
enter image description here
enter image description here
enter image description here
enter image description here

ASP.NET MVC 4 Website Deployment Error 404 - Application Name Missed in URL

I have looked in this site and seen some discussionsthe on error 404. But I can not find the same one as mine.
I have an application build with ASP.NET MVC 4. The url routing has not problem at all when I run in Visual Studio 2010. However when I published the application to Windows 2008 R2 Enterprise server named "MyCompany" under IIS7.5's Default Web Site as an application named "Test", the routing url misses the application name "Test". Thus causes the error 404.
The url is suppossed to be "http://MyCompany/Test/Home/Index?fileType=Fin". However it shows "http://MyCompany/Home/Index?fileType=Fin".
If I deploy the application to different port saying 8080, it works fine with "http://MyCompany:8080/Test/Home/Index?fileType=Fin".
Thanks in advance if anyone can help.
My route function is -
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
My WebServer configuration is -
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules runAllManagedModulesForAllRequests="true" />
<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>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="1048576000" />
</requestFiltering>
</security>
</system.webServer>
Update:
Robert reminded me of the Javascript potential problem. He is right. After reviewed my codes again, I found the location of the problem. This function -
function OnChange(dropdown) {
var myindex = dropdown.selectedIndex;
top.location.href = "Home/Index?fileType=" + dropdown.options[myindex].value;
return true;
}
should be -
function OnChange(dropdown) {
var myindex = dropdown.selectedIndex;
top.location.href = "#Url.Content("~/")" + "Home/Index?fileType=" + dropdown.options[myindex].value;
return true;
}
I'm going to go out on a limb, and say you've likely hard coded a URL in your javascript instead of using one of the URL building functions. There are a number of ways around that, but you need to verify that is the case first. We would need to see the Index view (or the offending javascript file) to see how you are building the URL to be able to determine what exactly is wrong.

How can I get ASP.NET MVC 4 to accept routes that look like filenames?

I'm working on a custom routing extension for ASP.NET MVC4 that uses reflection to generate routes based on attributes applied to controllers. It's a fork of Brandon Byars' RestMvc project and I'm updating it for .NET 4.5.
The attraction is that it allows one to write controllers that describe their own routes, like so:
public class EchoController : RestfulController
{
[Get("echo/{thingToEcho}.{format}", "echo/{thingToEcho}")]
public ActionResult Echo(string thingToEcho, string format)
{
if (format == "xml")
return new ContentResult
{
Content = string.Format("<echo>{0}</echo>", thingToEcho),
ContentType = MediaType.Xml
};
return new ContentResult
{
Content = thingToEcho,
ContentType = MediaType.PlainText
};
}
public override ActionResult Options(string resourceUri)
{
SetAllowHeader(resourceUri);
return new ContentResult {Content = "Options body goes here..."};
}
}
I'm running into a problem with routes in the format
[Get("echo/{thingToEcho}.{format}", "echo/{thingToEcho}")]
The idea here is that the client can make a request such as GET /echo/test.xml and the controller can then return a response in xml format instead of plain text, as demonstrated in the EchoController above.
In my fork of th eproject, all the routes are being correctly generated, but the "echo/{thingToEcho}.{format}" route doesn't work and I just get a 404 page. The same request but without the ".xml" works correctly and echoes back the expected text, so it seems like the route handler is doing its job, at least partly.
I'm a bit inexperienced with these technologies but I think this may be bound up with the handlers that are registered in the web.config file. In Brandon's original code targetting .NET 3.5 and MVC3, he has the following handlers:
<handlers>
<remove name="WebServiceHandlerFactory-Integrated"/>
<remove name="MvcHttpHandler"/>
<remove name="UrlRoutingHandler"/>
<add name="MvcHttpHandler" preCondition="integratedMode" verb="*" path="*.mvc" type="System.Web.Mvc.MvcHttpHandler, System.Web.Mvc, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add name="UrlRoutingHandler" preCondition="integratedMode" verb="*" path="UrlRouting.axd" type="System.Web.HttpForbiddenHandler, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
</handlers>
In my project, I wanted to get this working on top of the MVC4 basic Web App template, so I created a new MVC4 project and dropped Brandon's controller onto it. In the MVC4 web.config, the following handlers are registered:
<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>
Again, I haven't added these handlers, they are the defaults generated by the MVC4 project template.
Could this be the source of my problem? How would I solve this?

Resources