c# - 405 (Method Not Allowed) when POST from Angular 2 app
Your code seems ok.Try to change code as I have given below :
Angular
sendPtipo(delegacion: number,municipio: number,ejercicio: number,recinto: number,tipo: string){
let data = new Object();
data.delegacion = delegacion;
data.municipio = municipio;
data.ejercicio = ejercicio;
data.recinto = recinto;
data.tipo = tipo;
let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
let options = new RequestOptions({ headers: headers });
let urlPtipo ='http://localhost:50790/ApiProductoTipo/CalculaPTRecinto';
return this._http.post(urlPtipo , data , options)
.map(data => {alert('ok');})
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
return body.data || {};
}
private handleError(error: Response) {
console.error(error);
return Observable.throw(error.json().error || 'Server error');
}}
API in C#
using System.Collections.Generic;
using System.Web.Http;
using AppName.Models;
using AppName.Service;
using System.Linq;
using AppName.ViewModels;
using System.Net.Http;
using System.Net;
using System.Web.Http.Cors;
namespace Api.Services
{
// Allow CORS for all origins. (Caution!)
//[EnableCors(origins: "*", headers: "*", methods: "*")]
public class ApiProductoTipoController : ApiController
{
public class myobj{
public int delegacion { get; set; }
public int municipio { get; set; }
public int ejercicio { get; set; }
public int recinto { get; set; }
public string tipo { get; set; }
}
private readonly IProductoTipoService productoTipoService;
public HttpResponseMessage Options()
{
return new HttpResponseMessage { StatusCode = HttpStatusCode.OK };
}
public ApiProductoTipoController(IProductoTipoService productoTipoService)
{
this.productoTipoService = productoTipoService;
}
[HttpPost]
[Route("~/ApiProductoTipo/CalculaPTRecinto")]
public HttpResponseMessage CalculaPTRecinto(myobj data)
{
var tipo = data.tipo;
...
}
}}
I was facing the same issue.The actual datatype of data you sre sending can't get at API side.That's why its giving 405 error
.So try to send data as an object and also receive as an object at API side.
Hope this will help you
Aw3same
Sofware Engineer who want to do amazing things. Based on Angular and .NET. Improving my Big Data skills.
Updated on June 26, 2022Comments
-
Aw3same almost 2 years
I'm a bit desperate with this issue. I'm new on angular 2 and .net and I trying to build a simple application. I programmed an api rest in c#. When i call a GET method from angular it works fine, but not POSTmethod. I receive 405 (Method not allowed) all the time, but if i call the post with postman all works. I see lots of issues with the same problem, but they doesn't work for me. I have CORS enabled. Here's my code:
Angular
sendPtipo(delegacion,municipio,ejercicio,recinto,tipo){ let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' }); let options = new RequestOptions({ headers: headers }); let urlPtipo ='http://localhost:50790/ApiProductoTipo/CalculaPTRecinto'; let body ='delegacion='+delegacion+'&municipio='+municipio+'&recinto='+recinto+'&ejercicio='+ejercicio+'&tipo'+tipo; return this._http.post(urlPtipo , body , options) .map(data => {alert('ok');}) .catch(this.handleError); } private extractData(res: Response) { let body = res.json(); return body.data || {}; } private handleError(error: Response) { console.error(error); return Observable.throw(error.json().error || 'Server error'); }}
Api rest in C#
using System.Collections.Generic; using System.Web.Http; using AppName.Models; using AppName.Service; using System.Linq; using AppName.ViewModels; using System.Net.Http; using System.Net; using System.Web.Http.Cors; namespace Api.Services { // Allow CORS for all origins. (Caution!) //[EnableCors(origins: "*", headers: "*", methods: "*")] public class ApiProductoTipoController : ApiController { private readonly IProductoTipoService productoTipoService; public HttpResponseMessage Options() { return new HttpResponseMessage { StatusCode = HttpStatusCode.OK }; } public ApiProductoTipoController(IProductoTipoService productoTipoService) { this.productoTipoService = productoTipoService; } [HttpPost] [Route("~/ApiProductoTipo/CalculaPTRecinto")] public HttpResponseMessage CalculaPTRecinto([FromBody]int delegacion, int municipio, int ninterno, int ejercicio, string tipo) { if (this.productoTipoService.CalculaPTRecinto(delegacion, municipio, ninterno, ejercicio, tipo) != 0) { return Request.CreateResponse(HttpStatusCode.OK); } else { return Request.CreateResponse(HttpStatusCode.BadRequest); } } }}
webapiconfig.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web.Http; using System.Web.Http.Cors; namespace Web { public static class WebApiConfig { public static void Register(HttpConfiguration config) { //Enable cors var cors = new EnableCorsAttribute("*", "accept,accesstoken,authorization,cache-control,pragma,content-type,origin", "GET,PUT,POST,DELETE,TRACE,HEAD,OPTIONS"); //var cors = new EnableCorsAttribute("*", "*", "*"); config.EnableCors(cors); //Configuramos el MapRoute config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); config.Routes.MapHttpRoute( name: "ApiWithAction", routeTemplate: "{controller}/{action}/{id}", defaults: new { action = RouteParameter.Optional, id = RouteParameter.Optional } ); } } }
Log
headers:Headers ok:false status:405 statusText:"Method Not Allowed" type:2 url:"http://localhost:50790/ApiProductoTipo/CalculaPTRecinto" _body:"{"Message":"The requested resource does not support http method 'POST'."}"
Any idea? Thank you for reading!
Edit: this was the response of Postman 200 OK
Cache-Control →no-cache Content-Length →0 Date →Fri, 26 May 2017 09:48:05 GMT Expires →-1 Pragma →no-cache Server →Microsoft-IIS/10.0 X-AspNet-Version →4.0.30319 X-Powered-By →ASP.NET X-SourceFiles →=?UTF-8?B?QzpcVXNlcnNcNzAyNTU3MjFKXERlc2t0b3BcQXBpUHJvZHVjdG9UaXBvXFdlYlxBcGlQcm9kdWN0b1RpcG9cQ2FsY3VsYVBUUmVjaW50bw==?=
-
Aw3same almost 7 yearsThank you ! That works! But now i have another problem. Instead of use an object i use an array with this structure :
let data:Ptipo[] = []; data.push({'Delegacion':delegacion, 'Municipio':municipio, 'Ejercicio':ejercicio, 'Tipo_Producto':tipo, 'Ninterno':recinto});
but i don't get any value of the params :/ -
Darshita almost 7 years@Aw3same at server side you don't get value of params?
-
Aw3same almost 7 yearsYes, i have the method that you provide to me (
public class myobj
) and then get the value likevar delegacion = data.delegacion;
, but when i debug those params don't have any value -
Darshita almost 7 yearswhat do you get in data object in your
ts
file? -
Aw3same almost 7 yearsi have a class
ptipo.ts
that haveexport class Ptipo { Delegacion: Number; Municipio: number; Ejercicio: Number; Tipo_Producto: String; Ninterno: Number; }
. -
Aw3same almost 7 yearsThen, in my
service.ts
, the method postsendPtipo(delegacion,municipio,ejercicio,recinto,tipo){ let data:Ptipo[] = []; data.push({'Delegacion':delegacion, 'Municipio':municipio, 'Ejercicio':ejercicio, 'Tipo_Producto':tipo, 'Ninterno':recinto}); /*...*/ }
. I'm so noob with this languages, thanks for ur patient! -
Darshita almost 7 yearsit seems you have made model class. Then try to pass model in your method in
service.ts
. On submit button pass whole model instead of individual data , then no need to push data again.directly assign it to data object . e.g.sendPtipo(data){ }
.Here you will get direct data object. -
Aw3same almost 7 yearsYes, i have the object and the values inside them. But in the api, the values that asign to
var delegacion = data.delegacion;
of these object are 0 (number) and null (strings). I don't know if i get bad the values or what.. -
Darshita almost 7 yearsIt might be issue with your code or values you are sending.