HTTP 405 Errors after Publishing Web API 2 Applications - c#

I have a Web Api Controller and i have tested all actions on localhost and it works well.But when i Published it on Web Server,Just Actions with [HttpGet] works and [HttpPost] Actions return Http 405 error
public class ContentController : ApiController
{
[HttpGet]
public async Task<IHttpActionResult> AdvantageList()
{
//return ok 200
}
[HttpPost]
public async Task<IHttpActionResult> SaveAdvantage(ContentModel model)
{
//return 405
}
}
I used below method on client
var r = await ClientManager.Client.PostAsJsonAsync("api/Content/SaveAdvantage", Advantage);
But it will retrun below response form server.I Used PostAsJsonAsync method but it says that The requested resource does not support http method 'GET'
Does any one know why?
{
StatusCode: 405, ReasonPhrase: 'Method Not Allowed', Version: 1.0, Content: System.Net.Http.StreamContent, Headers:
{
Pragma: no-cache
X-Powered-By-Plesk: PleskWin
Connection: close
Cache-Control: no-cache
Date: Fri, 29 Sep 2017 08:53:51 GMT
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Content-Length: 72
Allow: POST
Content-Type: application/json; charset=utf-8
Expires: -1
}}
And
"{\"message\":\"The requested resource does not support http method 'GET'.\"}"
I have the below in my web api config:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{action}");
config.Routes.MapHttpRoute("WithId", "api/{controller}/{action}/{id}", new { id = RouteParameter.Optional });
config.Routes.MapHttpRoute("TwoId", "api/{controller}/{action}/{id}/{id2}", new { id = RouteParameter.Optional, id2 = RouteParameter.Optional });
config.MapHttpAttributeRoutes();
var formatter = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
formatter.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver();
}
}
I have below handlers in Web.config
<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>
I use this webapi2 application in my winform application.

It is the http error code who tell us that it is a right problem. Have a look at : https://fr.wikipedia.org/wiki/Liste_des_codes_HTTP

In hosting Setting in my web server ,had a property Preferred domain ,i changed it to none and after that it worked properly

You have a problem of right on the web server. 405 http code means that the post method is not allowed to use from your web server. Make you sure that you are authenticated when you send request and also make you sure that your request contain some token for authentication.

Related

Httppost and httpput blocked by CORS in .net core 3.1

I have a problem when i make httppost and httput (httpget is OK) to an API .net core 3.1 by an Angular 10 front, the error in console application is the famous :
Access to XMLHttpRequest at 'http://localhost:23645/api/Toolbar/Search' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
capture
this the code of my front request :
constructor(private Http: HttpClient) {
this.header = new HttpHeaders(
{
'content-type': 'application/json'
}
)
searchToolbar(search: string): Observable<ToolbarSearchResultItem[]> {
return this.Http.post(this.url + '/myController/Search', { "search": search }, { headers: this.header, withCredentials:true}).pipe(tap((response: myTyoe[]) => {
return response;
}));
this is my code in Startup.cs :
public void ConfigureServices(IServiceCollection services)
{
log.Info("ConfigureServices");
try
{
IConfigurationRoot configurationRoot = builder.Build();
services.AddCors(opt => opt.AddPolicy("CorsPolicy", c =>
{
c.WithOrigins("http://localhost:4200")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
}));
services.AddAuthorization(options =>
{
options.AddPolicy("AllUsers", policy => policy.RequireAuthenticatedUser());
});
services.AddControllers();
services.AddMvc();
}
catch (Exception ex)
{
log.Error("Error in ConfigureServices" + ex.Message + ex.StackTrace);
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
try
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseCors("CorsPolicy");
app.UseAuthorization();
in a launchSettings.json i set this :
"iisSettings": {
"windowsAuthentication": true,
"anonymousAuthentication": false,
"iisExpress": {
"applicationUrl": "http://localhost:23645",
"sslPort": 0
}
and in applicationhost.config:
<windowsAuthentication enabled="true">
<providers>
<add value="Negotiate" />
<add value="NTLM" />
</providers>
</windowsAuthentication>
this is my controller:
[HttpPost]
[Route("Search")]
[EnableCors("CorsPolicy")]
public IList<ToolbarSearchResultItem> Search(ToolbarSearch search)
{
//my code
}
this is the detailled message in the console :Request URL: http://localhost:23645/api/Toolbar/Search
Request Method: OPTIONS
Status Code: 401 Unauthorized
Remote Address: [::1]:23645
Referrer Policy: strict-origin-when-cross-origin
Cache-Control: private
Content-Length: 6284
Content-Type: text/html; charset=utf-8
Date: Tue, 02 Mar 2021 15:52:05 GMT
Server: Microsoft-IIS/10.0
WWW-Authenticate: Negotiate
WWW-Authenticate: NTLM
X-Powered-By: ASP.NET
Accept: /
Accept-Encoding: gzip, deflate, br
Accept-Language: fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7
Access-Control-Request-Headers: content-type
Access-Control-Request-Method: POST
Connection: keep-alive
Host: localhost:23645
Origin: http://localhost:4200
Referer: http://localhost:4200/
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-site
this is my web.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<location path="." inheritInChildApplications="false">
<system.webServer>
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
</handlers>
<aspNetCore processPath=".\MYEXE.exe" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" hostingModel="inprocess" />
</system.webServer>
</location>
</configuration>
I think that it is not really a CORS block problem but a configuration problem or other, it is very similar to this question : Trouble with CORS Policy and .NET Core 3.1
but I used a profiler and I don't have an SQL Problem
Remove from your startup Cors config
.AllowCredentials();
and remove from the controller actions
[EnableCors("CorsPolicy")]
But you still have have Status Code: 401. It has nothing to do with Cors. It is only about authorization. Just comment all authorization code to test CORS. After this you can start with authorization.
Access to XMLHttpRequest at 'http://localhost:23645/api/Toolbar/Search' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Please note that a CORS preflight request (using the HTTP OPTIONS method) is used to check whether the CORS protocol is understood and a server is aware using specific methods and headers. And the HTTP OPTIONS requests are always anonymous, you enabled Windows Authentication and disabled anonymous access, which would cause server not correctly respond to the preflight request.
To run your app(s) on local for testing purpose with CORS, to fix this issue, you can try to enable anonymous authentification to allow anonymous access.
Besides, if you would host your app(s) on IIS server, to fix this issue, you can install IIS CORS module and configure CORS for the app.

Asp.Net MVC WebApi CORS Request fails - no proposed solutions affecting the outcome

I have an Asp.Net NVC5 web application (running under Visual Studio 2017) on localhost:59569 (SiteApi). I have a second website (also running under Visual Studio 2017) on localhost:61527 (SiteClient) where a page once loaded makes the following api call to SiteApi:
$http({
url: 'http://localhost:59569/api/V2/' + alias,
method: 'POST',
data: pm,
xhrFields: { withCredentials: true },
headers: { 'Content-Type': 'application/json; charset=utf-8' }
})
.then(th, ex);
NOTE: I have tried this with and without the xhrFields + withCredentials information using Microsoft IE, Microsoft Edge and Chrome.
Back on SiteApi the resulting preflight call for OPTIONS is intercepted by the following code in Global.asax which executes exactly as written and I can trace through the if statement when an inbound call for OPTIONS triggers it.
protected void Application_BeginRequest()
{
if (Request.Headers.AllKeys.Contains("Origin") && Request.HttpMethod == "OPTIONS")
{
Response.Clear();
Response.Headers.Add("Access-Control-Allow-Origin", "*");
Response.Headers.Add("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With, Session");
Response.Flush();
Response.End();
}
}
The intention being to send the desired headers back to the client to allow CORS to function properly - however immediately after this code is executed the web page back on SiteClient reports that the request has been blocked due to missing 'Access-Control-Allow-Origin' header is missing and I can see that none of the headers I have specified have made it back to the client.
In an attempt to have CORS work I have the following nuget packages installed on the SiteAPI project.
Microsoft.AspNet.Cors
Microsoft.AspNet.WebApi.Cors
I adjusted the WebApiConfig.Register() method to include:
// Web API configuration and services
config.EnableCors();
I have tried many variations of adding the filter attributes to my controller like so:
[EnableCors("*", "*", "*", SupportsCredentials = true)]
I have tried adding my own custom ActionFilterAttribute from solutions found in other CORS related questions on stackoverflow - for example (among various others):
public override void OnActionExecuting(System.Web.Mvc.ActionExecutingContext filterContext)
{
filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "*");
base.OnActionExecuting(filterContext);
I have the following to my web.config file:
<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>
I have ALL these solutions live in my project and in spite of this I still get CORS errors on the client side.
So the caveat here is that I also have a custom filter that looks up security on each API call - which works fine with ALL calls made from pages running on SiteApi. In the case of calls from SiteClient (CORS calls) the security filter never fires at all though I am getting 401 errors reported on the client in addition to the errors due to the missing CORS related headers.
I have cleared the caches of all browsers and the server itself. This is my first time working with CORS and I'm already exhausted from working with what really should be a simple solution. Looking for solutions here and would appreciate some help from those in the know.
Request Headers:
Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Connection: keep-alive
Content-Length: 2
Content-Type: application/json; charset=UTF-8
Host: localhost:59569
Origin: http://localhost:61527
Referer: http://localhost:61527/Home/Index
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-site
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.106 Safari/537.36 Edg/80.0.361.54
Response Headers:
Cache-Control: private
Content-Length: 6115
Content-Type: text/html; charset=utf-8
Date: Wed, 19 Feb 2020 00:46:06 GMT
Server: Microsoft-IIS/10.0
WWW-Authenticate: Negotiate
WWW-Authenticate: NTLM
X-Powered-By: ASP.NET
X-SourceFiles: =?UTF-8?B?QzpcVXNlcnNcbngyMDA4MjZcRGV2XFRlY2hJVFxFQVNJV2ViQXBwXGFwaVxWMlxHZXRDb21tYW5kcw==?=
This is the flow I use. Sometimes browsers don't like "*". Other times, browsers don't like localhost, either. This is the logic I use (modify the allow headers as you see fit). It could be the fact that you aren't allowing the access control headers in your allowed headers, too:
[Add this to Global.asax]
protected void Application_BeginRequest(object sender, EventArgs e)
{
var originKey =
Request.Headers.AllKeys.FirstOrDefault(
a => a.Equals("origin", StringComparison.InvariantCultureIgnoreCase));
if (originKey != null && Request.HttpMethod == "OPTIONS"))
{
// Optional Whitelist check here can return without the headers below to reject CORS
Response.Headers.Add("Access-Control-Allow-Origin", Request.Headers[originKey]);
Response.Headers.Add("Access-Control-Allow-Credentials", "true");
Response.Headers.Add("Access-Control-Allow-Methods", "GET, POST, PUSH, DELETE, OPTIONS");
Response.Headers.Add("Access-Control-Allow-Headers",
"Authorization, Content-Type, Access-Control-Allow-Headers, X-Requested-With, Access-Control-Allow-Method, Accept");
Response.Flush();
Response.End();
return;
}
}

WEB API error-404 - "Message": "The requested resource does not support http method 'PUT'."

HTTP/1.1 405 Method Not Allowed
Cache-Control: no-cache
Pragma: no-cache
Allow: GET,POST
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?QzpcUHJvamVjdHNcZG90TmV0XFdlYkFQSVxBZFNlcnZpY2VcQWRTZXJ2aWNlXGFwaVxpbXByZXNzaW9uXDE1?=
X-Powered-By: ASP.NET
Date: Tue, 06 May 2014 14:10:35 GMT
Content-Length: 72
{"message":"The requested resource does not support http method 'PUT'."}
I want to generate PUT and DELETE request using POSTMAN but I got following message from POSTMAN.
Even I have implemented all the suggestions given by ASP.NET site.
Below is Web API c# code:
// PUT: api/Students/5
[HttpPut]
[ResponseType(typeof(void))]
public IHttpActionResult PutStudent(decimal Enrollment_no, Student student)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (Enrollment_no != student.Enrollment_no)
{
return BadRequest();
}
db.Entry(student).State = EntityState.Modified;
try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException)
{
if (!StudentExists(Enrollment_no))
{
return NotFound();
}
else
{
throw;
}
}
return StatusCode(HttpStatusCode.NoContent);
}
Nothing has worked as I'm still getting a 405 response when trying to issue a "PUT" command against my Web API project.
Your back end api is only allowing GET and POST requests(see response header Allow ), hence to generate PUT/DELETE request API should add support for the same.
You can configure this by modifying web.config of your ASP.NET Web API. Try to find the following line:
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
Replace it with:
<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" />
Please refer here for more information.

ASP.NET Web API application returns HTTP 500 for non existant routes with TransferRequestHandler enabled

I created a simple Web API app (empty template from Visual Studio with Web API enabled), added a controller:
[RoutePrefix("api/test")]
public class TestController : ApiController
{
[HttpGet]
[Route(#"resource/{*path?}")]
public async Task<HttpResponseMessage> GetFolder(string path = "")
{
return this.Request.CreateResponse(HttpStatusCode.OK, new { Status = "OK" });
}
}
Now we need to support file name extensions (e.g. file.pdf) in the path variable, so I modified the web.config:
<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" />
<!-- API must handle all file names -->
<add name="ApiUrlHandler" path="/api/test/*" verb="GET,POST,PUT,DELETE,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
The problem now is that the HTTP status codes are inconsistents, depending on the URL segments provided after the prefix /api/test/:
GET /api/test/resource => HTTP 200 (as expected)
GET /api/test/resource/foo => HTTP 200 (as expected)
GET /api/test/foo => HTTP 404 (as expected)
GET /api/test/foo/bar => HTTP 500 (expected: 404)
The 500 error page is displayed in HTML and nothing is logged in the application logs, no exception thrown. I am using VS 2015, with .NET framework 4.5.1.
I am seeing this as well - and I see that my global.asax.cs "BeginRequest" and "EndRequest" is called around 10 times for requests like these. Looks like an ASP.NET/WebApi bug.
The solution I found was to register a "catch all" route with a controller that always returns a 404.
config.Routes.MapHttpRoute(
name: "CatchAllRoute",
routeTemplate: "{*catchall}",
defaults: new { controller = "UnrecognizedRoute", action = ApiConstants.UnrecognizedRouteAction });
...
public class UnrecognizedRouteController : ApiController
{
/// <summary>
/// This method is called for every single API request that comes to the API and is not routed
/// </summary>
[ActionName(ApiConstants.UnrecognizedRouteAction)]
[HttpDelete, HttpGet, HttpHead, HttpOptions, HttpPost, HttpPatch, HttpPut]
public IHttpActionResult ProcessUnrecognizedRoute()
{
return NotFound();
}
}

WebApi HttpPost not working on Windows Azure

I am working on a sample project using WebApi2 with MVC with Angular and D3 api. I am facing an issue with my WebApi. Everything working fine on local machine with Azure database connection string but when i publish the same on Azure my HttpPost stops working while HttpGet is working fine.
[HttpPost]
[Route("api/dashboard/addnewassignment")]
public WebApiD3Sample.ViewModels.CoursePersonAssignmentModel AddNewCoursePersonAssignment([FromBody]WebApiD3Sample.ViewModels.CoursePersonAssignmentModel model)
{
if (ModelState.IsValid) {
var modelAfterSave = AssignmentService.AddAssignment(model);
return modelAfterSave;
}
ModelState.AddModelError("Invalid", "Not a Valid Save");
return model;
}
Error that i am facing on published
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
http://sampledataweb.azurewebsites.net/api/dashboard/addnewassignment
Object
message: "An error has occurred."
__proto__: Object
I could send a post to your URL:
Status Code: 200 OK
Access-Control-Allow-Headers: Origin,X-Requested-With,Content-Type,Accept
Access-Control-Allow-Origin: *
Cache-Control: no-cache
Content-Encoding: gzip
Content-Length: 123
Content-Type: application/json; charset=utf-8
Date: Thu, 06 Mar 2014 18:48:25 GMT
Expires: -1
Pragma: no-cache
Server: Microsoft-IIS/8.0
Set-Cookie: ARRAffinity=dbb5756ce35e0494cf70c90b9aba80f70f92f607fb3ebb3e7dffe4ecc1aba24a;Path=/;Domain=sampledataweb.azurewebsites.net WAWebSiteSID=696c72c37b2e472b90f6033923558edd; Path=/; HttpOnly
Vary: Accept-Encoding
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
so the problem is in your CoursePersonAssignmentModel or AssignmentService.AddAssignment method. Install a nuget to log (i.e Elmah) and it will help you to catch the error. Another great option, you can debug using intellitrace: http://blogs.msdn.com/b/zainnab/archive/2013/02/12/understanding-intellitrace-part-i-what-the-is-intellitrace.aspx
It doesn't appear to be a cross domain issue, but just to make sure, did you allow it in your web.config?
<system.webServer>
<httpProtocol>
<customHeaders>
<remove name="Access-Control-Allow-Origin" />
<remove name="Access-Control-Allow-Headers" />
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Origin,X-Requested-With,Content-Type,Accept" />
</customHeaders>
</httpProtocol>
</system.webServer>

Categories

Resources