2017-05-26 114 views
3

我有點絕望這個問題。我是新的角2和.net,我試圖建立一個簡單的應用程序。我在c#中編寫了api rest。當我從角度調用GET方法時,它工作正常,但不是POSTmethod。我總是收到405(方法不允許),但是如果我和郵遞員一起打電話給所有作品。我發現許多問題都出在同一個問題上,但他們對我來說並不合適。 我啓用了CORS。 這裏是我的代碼:c# - 405(方法不允許)當從角2應用POST POST

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'); 
}} 

阿比休息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 } 
      ); 
     } 


    } 
} 

登錄

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'."}" 

任何想法?感謝您的閱讀!

編輯:這是郵差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==?= 
+0

你的郵遞員請求是什麼樣的? –

回答

6

你的代碼似乎ok.Try更改代碼,我已經給下面:

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'); 
    }} 

C#中的API

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; 
      ... 
     } 
    }} 

我面臨同樣的數據issue.The實際的數據類型,你SRE發送的API side.That的不能明白爲什麼它給405 error。那麼嘗試發送數據作爲對象,也接收爲對象在API方面。

希望這會幫助你

+0

謝謝!這樣可行!但現在我有另一個問題。而不是使用一個對象,我使用這種結構的數組: 'let data:Ptipo [] = []; data.push({ 'Delegacion':delegacion, 'MUNICIPIO':MUNICIPIO, 'Ejercicio':ejercicio, 'Tipo_Producto':TIPO, 'Ninterno':recinto});' 但我不明白任何值的參數:/ – Aw3same

+0

@ Aw3same在服務器端,你沒有得到params的價值? – Darshita

+0

是的,我有你提供給我的方法('公共類myobj'),然後得到像'var delegacion = data.delegacion;'的值,但是當我調試那些參數沒有任何價值 – Aw3same

相關問題