WebApi + AngularJS:405方法不允许

时间:2016-07-28 19:15:05

标签: angularjs web-config asp.net-web-api2

我遇到了问题,虽然我已经看到很多相同主题的答案但没有真正奏效。我有一个WebAPI项目和一个我有Angular的MVC。

从Angular项目中,我试图发布这样的内容:

var promise = $http.post("http://localhost:55692/api/users", user)
                .success(function (data) {
                    debugger;
                    console.log(data);
                    return data;
                });

            $http(
        {
            url: "http://localhost:55692/api/users",
            method: "POST",
            headers: { 'Content-Type': 'application/json' },
            data: { "user": user }
        })
            .then(function (response) {
                debugger;
                console.log(data);
                return data;
            });
            return promise;

如果你看到,我正在调用两次相同的API,以防它是一个Angular的东西,但对我来说,它不是......

我的API项目中有这个控制器:

[RoutePrefix("api/users")]
    public class ValuesController : ApiController
    {
        [Route("")]
        [HttpPost]
        public HttpResponseMessage LoginOrRegister(RegisterUserViewModel user)
        {
            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, true);
            return response;
        }
    }

这是我的回应:

Response

这是我的WebConfig

<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>
    <!--<validation validateIntegratedModeConfiguration="false" />-->
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept, X-Token, X-Acting-As" />
        <add name="Access-Control-Allow-Methods" value="GET,POST,PUT,DELETE,OPTIONS,PATCH" />
      </customHeaders>
    </httpProtocol>
  </system.webServer>

修改 我的WebApiConfig看起来像这样:

public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Attribute routing enabled
            config.MapHttpAttributeRoutes();

            // Convention-based routing enabled
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            config.Formatters.JsonFormatter.SerializerSettings.NullValueHandling = NullValueHandling.Include;

            // Uncomment the following line of code to enable query support for actions with an IQueryable or IQueryable<T> return type.
            // To avoid processing unexpected or malicious queries, use the validation settings on QueryableAttribute to validate incoming queries.
            // For more information, visit http://go.microsoft.com/fwlink/?LinkId=279712.
            //config.EnableQuerySupport();

            // To disable tracing in your application, please comment out or remove the following line of code
            // For more information, refer to: http://www.asp.net/web-api
            config.EnableSystemDiagnosticsTracing();
        }
    }

最后,唯一“奇怪”的是我正在使用IISExpress,因为这些是我项目的第一步......

有谁知道会发生什么?

2 个答案:

答案 0 :(得分:3)

经过多次努力,这就是它......

    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Attribute routing enabled
            config.MapHttpAttributeRoutes();

            // Convention-based routing enabled
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            config.Formatters.JsonFormatter.SerializerSettings.NullValueHandling = NullValueHandling.Include;
            config.MessageHandlers.Add(new PreflightRequestsHandler()); 
}
    }

预检班:

public class PreflightRequestsHandler : DelegatingHandler
    {
        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            if (request.Headers.Contains("Origin") && request.Method.Method.Equals("OPTIONS"))
            {
                var response = new HttpResponseMessage { StatusCode = HttpStatusCode.OK };
                // Define and add values to variables: origins, headers, methods (can be global)               
                response.Headers.Add("Access-Control-Allow-Headers", "accept, content-type");

                var tsc = new TaskCompletionSource<HttpResponseMessage>();
                tsc.SetResult(response);
                return tsc.Task;
            }
            return base.SendAsync(request, cancellationToken);
        }

    }

我希望这可以帮助其他人!

答案 1 :(得分:0)

当您的请求数据类型不受支持时,会出现

405。您需要在以下

中传递内容类型
private headers = new Headers({ 'Content-Type': 'application/json' });
private options = new RequestOptions({ headers: this.headers });

return this.http.post(this.baseUserUrl + '/Save', JSON.stringify(user), this.options)
            .toPromise()
            .then(response => response)
            .catch((error) => Promise.reject(error));

并在API层

 public async Task<HttpResponseMessage> Save(UserDto user)

 public HttpResponseMessage Save(UserDto user)