I have this very common issue where it says method not allowed (OPTIONS) for a GET request. I am getting the following error whenever I make an API call. I have this setting in web.config:
<system.webServer>
<modules>
<remove name="WebDAVModule"/>
</modules>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*"/>
<add name="Access-Control-Allow-Headers" value="Origin, Authorization, X-Requested-With, Content-Type, Accept"/>
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS"/>
</customHeaders>
</httpProtocol>
<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 tried using Asp.Net.WebApi.Cors and enforcing CORS globally using EnableCors() for all origin headers and methods and that did not work either.
In your handlers after <remove name="OPTIONSVerbHandler"/>, add this:
<add name="OPTIONSVerbHandler" path="*" verb="OPTIONS"
modules="IsapiModule" requireAccess="None"
scriptProcessor="C:\Windows\System32\inetsrv\asp.dll"
resourceType="Unspecified" />
See the answer at IIS hijacks CORS Preflight OPTIONS request.
Or maybe even just this:
<add name="OPTIONSVerbHandler" path="*" verb="OPTIONS"
modules="ProtocolSupportModule" requireAccess="None" />
If that doesn’t work, something that will is adding the following in your global.asax or other code:
protected void Application_BeginRequest(object sender,EventArgs e)
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
if(HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000" );
HttpContext.Current.Response.End();
}
}
Related
I have web.api 2 project. I also tried to add handler to it. But every request (http://api.xxxx.xxx/handler) which I send return error of 404 code. I realized that problem is route config, but how I can fix it?
web.config
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules runAllManagedModulesForAllRequests="true">
<remove name="WebDAVModule" />
<!-- ADD THIS -->
</modules>
<handlers accessPolicy="Read, Execute, Script">
<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="ChatHandler" verb="*" path="/handler/" type="ProjectAPI.Handler.ChatHandler" />
</handlers>
</system.webServer>
Global.asax.cs
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
RouteTable.Routes.Ignore("{resource}.axd/{*pathInfo}");
RouteTable.Routes.Ignore("handler/{*path}");
GlobalConfiguration.Configure(WebApiConfig.Register);
}
}
If you didn't changed the WebApiConfig routes, the default url should be:
http://api.xxxx.xxx/api/handler. I've never see a need to add this to the configuration, why's that? Change only the configuration in the WebApiConfig.Register from ~/api/ to ~/ and it should work. Post some more code, because it's like "reading from the tea leaves" :)
I'm building Angular 5 app with asp.net backend. I want to send POST request, I tested it via Postman and it works absolutely fine, however, when I try to do it inside Angular I get 405 error.
I user HttpClient with headers: new HttpHeaders({ 'Content-Type': 'application/json' }), same as Postman.
I tried to change web.config
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*"/>
<add name="Access-Control-Allow-Headers" value="Origin, Authorization, X-Requested-With, Content-Type, Accept"/>
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS"/>
</customHeaders>
</httpProtocol>
<validation validateIntegratedModeConfiguration="false"/>
<modules runAllManagedModulesForAllRequests="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>
but it seems it does not work.
Angular POST code (with headers: new HttpHeaders({ 'Content-Type': 'application/json' })
setDopuskItem(itemToSave: DopuskItem){
let endpoint = this._dopuskApiUrl + 'set';
let body = JSON.stringify(itemToSave);
return this.http.put(
endpoint,
body,
httpOptions)
.catch(this.handleError);
}
it's because the browsers send preflight request before send main request.
you can add following code to your webapi app: global.asax.cs
protected void Application_BeginRequest()
{
if (Request.HttpMethod == "OPTIONS") {
Response.Flush();
}
}
Briefly:
Bundles which contain items from a VirtualPath (Served by custom VirtualPathProvider) don't work. Hash isn't generated in the v= and resolving them shows the .Items property as empty.
Detailed:
Suppose we have a bundle registration:
bundles.Clear();
bundles.ResetAll();
BundleTable.EnableOptimizations = true;
bundles.Add(new StyleBundle("~/bundles/css")
.Include("~/Content/site.css"));
bundles.Add(new StyleBundle("~/bundles/admin/somestyle")
.Include("~/Areas/Admin/Content/css/aaa2.css"));
Some notes here:
~/bundles/admin/somestyle physically doesn't exist.
~/Areas/Admin/Content/css/aaa2.css is a virtual path which is handled by a custom VirtualPathProvider
~/bundles/css is served by default MapPathBasedVirtualPathProvider
Relevant part of current Web.config file:
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules runAllManagedModulesForAllRequests="false"/>
<handlers>
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<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" />
<add name="AspNetStaticFileHandler-TIFF" path="*.tiff" verb="*" type="System.Web.StaticFileHandler" />
<add name="AspNetStaticFileHandler-GIF" path="*.gif" verb="*" type="System.Web.StaticFileHandler" />
<add name="AspNetStaticFileHandler-PNG" path="*.png" verb="*" type="System.Web.StaticFileHandler" />
<add name="AspNetStaticFileHandler-JPG" path="*.jpg" verb="*" type="System.Web.StaticFileHandler" />
<add name="AspNetStaticFileHandler-CSS" path="*.css" verb="*" type="System.Web.StaticFileHandler" />
<add name="AspNetStaticFileHandler-JS" path="*.js" verb="*" type="System.Web.StaticFileHandler" />
<add name="AspNetStaticFileHandler-WOFF" path="*.woff" verb="*" type="System.Web.StaticFileHandler" />
<add name="AspNetStaticFileHandler-TTF" path="*.ttf" verb="*" type="System.Web.StaticFileHandler" />
<add name="AspNetStaticFileHandler-MAP" path="*.map" verb="*" type="System.Web.StaticFileHandler" />
</handlers>
</system.webServer>
Routing entries:
routes.IgnoreRoute("favicon.ico");
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
Test Drive:
1. Trying to access the .css files directly:
http://localhost:1010/Areas/Admin/Content/css/aaa2.css - File found => Custom VirtualPathProvider did his job.
2. Trying to resolve bundles from HomeController:
public ActionResult Test()
{
var bundleVirtual = BundleTable.Bundles.GetBundleFor("~/bundles/admin/somestyle");
var bundleVirtualUrl = BundleTable.Bundles.ResolveBundleUrl("~/bundles/admin/somestyle");
var bundleOrdinary = BundleTable.Bundles.GetBundleFor("~/bundles/css");
var bundleOrdinaryUrl = BundleTable.Bundles.ResolveBundleUrl("~/bundles/css");
return View();
}
bundleVirtual is found but .Items property is empty.
bundleVirtualUrl is /bundles/admin/somestyle?v= notice that v= has no hash value.
bundleOrdinary is found, .Items has one entry ~/Content/site.css.
bundleOrdinaryUrl is "/bundles/css?v=6bMbVqKBetPV3UISUSkpqR5wiBsbzK_c6J21LUZAzaU1"
Question:
Why resolving "~/bundles/admin/somestyle" shows that there are not Items added, even if the item is registered and the VirtualPathProvider handles it correctly?
Related links:
ASP.NET Bundling/Minification and Embedded Resources
http://www.codeproject.com/Articles/728146/ASP-NET-MVC-bundles-internals
You need to register your VirtualPathProvider before bundle registration, in order to be able to find your files. Any files not found will not be included in bundle.Items
var vpp = new MyVirtualPathProvider();
BundleTable.VirtualPathProvider = vpp;
BundleConfig.RegisterBundles(BundleTable.Bundles);
Unless of course you already have it registered as HostingEnvironment.VirtualPathProvider.
i'm using web api with asp.net web forms 4.5 and i have problem in delete method .
that not work but other methods work good.
please help .
this my delete method:
[HttpDelete]
public void DeleteConversation(long id)
{
if (_repository.UserConvers(long.Parse(User.Identity.GetUserId())).All(a => a.Id != id))
return;
var item = _repository.Get(id);
if (item == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
_repository.Remove(id);
}
and this is my web config :
<modules runAllManagedModulesForAllRequests="true">
<remove name="FormsAuthenticationModule" />
<remove name="WebDAVModule"/>
</modules>
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="CKUpload" path="/Handlers/CKUpload.ashx" verb="*" type="UI.Handlers.CKUpload,UI" />
<add path="Captcha.ashx" verb="*" name="Captcha" type="UI.Handlers.Captcha,UI" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
Make sure that inside your delete method in _repository class that you are calling SaveChanges(). Nothing wrong with your Method and you should be able to access it by issuing HTTP Delete to uri "/api/{controllerName}/45541"
I have a DotNetNuke 7 website and I have enabled custom errors like so:
<customErrors mode="On" defaultRedirect="Error.aspx">
<error statusCode="404" redirect="FileNotFound.aspx" />
</customErrors>
I also want to add such errors for extension less URLs but when I try to add a wildcard mapping it breaks the site with 404 on the http://mysite.com etc
<add name="WILDCARDMAPPING" path="*" verb="*" type="" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="None" allowPathInfo="false" preCondition="integratedMode,bitness64" />
How do I setup the handlers..
<handlers accessPolicy="Read, Execute, Script">
<remove name="WebServiceHandlerFactory-Integrated" />
<add name="LogoffHandler*" path="Logoff.aspx" verb="*" type="DotNetNuke.Services.Authentication.LogOffHandler, DotNetNuke" preCondition="integratedMode" />
<add name="RSSHandler" path="RSS.aspx" verb="*" type="DotNetNuke.Services.Syndication.RssHandler, DotNetNuke" preCondition="integratedMode" />
<add name="LinkClickHandler" path="LinkClick.aspx" verb="*" type="DotNetNuke.Services.FileSystem.FileServerHandler, DotNetNuke" preCondition="integratedMode" />
<add name="CaptchaHandler" path="*.captcha.aspx" verb="*" type="DotNetNuke.UI.WebControls.CaptchaHandler, DotNetNuke" preCondition="integratedMode" />
<add name="UserProfilePageHandler" path="User.aspx" verb="*" type="DotNetNuke.Services.UserProfile.UserProfilePageHandler, DotNetNuke" preCondition="integratedMode" />
<add name="RadProgressHandler" verb="*" path="Telerik.RadUploadProgressHandler.ashx" type="Telerik.Web.UI.Upload.RadUploadProgressHandler, Telerik.Web.UI" preCondition="integratedMode" />
<add name="UserProfilePicHandler" path="ProfilePic.ashx" verb="*" type="DotNetNuke.Services.UserProfile.UserProfilePicHandler, DotNetNuke" preCondition="integratedMode" />
<remove name="ExtensionlessUrl-Integrated-4.0" />
<add name="ExtensionlessUrl-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
<add name="SitemapHandler" path="Sitemap.aspx" verb="*" type="DotNetNuke.Services.Sitemap.SitemapHandler, DotNetNuke" preCondition="integratedMode" />
<add name="ClientDependencyHandler" verb="*" path="DependencyHandler.axd" type="ClientDependency.Core.CompositeFiles.CompositeDependencyHandler, ClientDependency.Core" preCondition="integratedMode" />
<add name="Telerik.Web.UI.WebResource" verb="*" path="Telerik.Web.UI.WebResource.axd" type="Telerik.Web.UI.WebResource, Telerik.Web.UI" preCondition="integratedMode" />
<add name="Telerik.Web.UI.ChartHttpHandler" verb="*" path="ChartImage.axd" type="Telerik.Web.UI.ChartHttpHandler, Telerik.Web.UI, Culture=neutral, PublicKeyToken=121fae78165ba3d4" />
<add name="HtmTemplateFileHandler" verb="*" path="*.htmtemplate" type="DotNetNuke.Providers.RadEditorProvider.HtmTemplateFileHandler, DotNetNuke.RadEditorProvider" preCondition="integratedMode" />
<add name="WILDCARDMAPPING" path="*" verb="*" type="" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="None" allowPathInfo="false" preCondition="integratedMode,bitness64" />
</handlers>
I have tried movie the WILDCARDMAPPING handler I added to the top, middle but it doesnt work.
DNN already provides support for extension less urls when there is a page that has been added to the CMS like /Home but shows the normal 404 error message for /somepage.
Just add to each directory an index.html that shows what you would like to display for that case - by default opening http://SomeUrl/some/path/ always opens/tries to open http://SomeUrl/some/path/index.html
This works:
<system.webServer>
<httpErrors>
<remove statusCode="404" subStatusCode="-1" />
<error statusCode="404" path="/FileNotFound.aspx" responseMode="ExecuteURL" />
</httpErrors>
</system.webServer>
DNN 7.1 includes the new "Advanced URL Provider" (based on iFinity's URL Master extension), which includes built-in support for 404 pages & extension-less URLs. There is a page called "404 Error Page" in a new DNN 7.1 site (you have to create it manually in an upgraded site, see the accepted answer at http://www.dnnsoftware.com/answers/cid/350985), which will be returned for pages that aren't found (whether there's an extension or not).
Related:
DNN 404 Handling article on DNN's wiki
Blog post on 404 handling