从Angular 2应用程序POST时出现C# - 405(方法不允许)错误

6

我对这个问题感到有些绝望。我刚接触angular 2和.net,正在尝试构建一个简单的应用程序。我使用c#编写了一个rest api。当我从angular调用GET方法时,它可以正常工作,但是POST方法不行。每次都会收到405 (Method not allowed)的错误提示,但是如果我在postman中调用post请求,则一切正常。我看到很多类似的问题,但它们对我不起作用。 我已经启用了CORS。 这是我的代码:

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

使用C#实现REST 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
    {
        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'."}"

任何想法?谢谢你的阅读! 编辑:这是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==?=

你的Postman请求是什么样子的? - J.N.
1个回答

6
你的代码似乎没什么问题。尝试按照我以下给出的方式更改代码:
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');
    }}

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

我曾经遇到过同样的问题。你所发送的数据实际数据类型无法在API端获取,这就是为什么它会返回405错误。因此,请尝试将数据作为对象发送并在API端接收对象。
希望这能帮助到您。

谢谢!这个方法可行!但是现在我又有了一个问题。我不是使用对象,而是使用了一个具有以下结构的数组: let data:Ptipo[] = []; data.push({'Delegacion':delegacion, 'Municipio':municipio, 'Ejercicio':ejercicio, 'Tipo_Producto':tipo, 'Ninterno':recinto}); 但是我没有得到任何参数的值 :/ - Aw3same
@Aw3same,在服务器端你没有收到参数的值吗? - Darshita
是的,我有你提供给我的方法(public class myobj),然后像这样获取值 var delegacion = data.delegacion;,但是当我调试这些参数时,它们没有任何值。 - Aw3same
在你的 ts 文件中,数据对象中包含什么? - Darshita
然后,在我的 service.ts 文件中,有一个名为 sendPtipo(delegacion,municipio,ejercicio,recinto,tipo) 的 post 方法。代码如下:let data:Ptipo[] = []; data.push({'Delegacion':delegacion, 'Municipio':municipio, 'Ejercicio':ejercicio, 'Tipo_Producto':tipo, 'Ninterno':recinto}); /*...*/我对这些语言不是很熟悉,感谢您的耐心! - Aw3same
显示剩余4条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接