简体   繁体   English

WebApi + AngularJS:405方法不允许

[英]WebApi + AngularJS: 405 Method Not Allowed

I'm having a problem and although I've seen plenty of answers to the same topic nothing really worked.. I have a WebAPI project and an MVC one where I have Angular. 我遇到了一个问题,尽管我已经看到很多有关同一主题的答案,但实际上没有任何用处。.我有一个WebAPI项目,一个有Angular的MVC项目。

From the Angular project, I'm trying to post something like this: 在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;

If you see, I'm calling the same API twice in case it's an Angular thing but to me, it's not.. 如果看到的话,我会两次调用相同的API以防万一是Angular的事情,但对我来说不是。

I have this controller in my API project: 我的API项目中有这个控制器:

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

This is the response I have: 这是我的回应:

Response 响应

And this is my WebConfig 这是我的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>

EDIT My WebApiConfig looks like this: 编辑我的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();
        }
    }

Finally, the only thing "weird" is that I'm using IISExpress as these are the first steps of my project.. 最后,唯一奇怪的是我正在使用IISExpress,因为这是我项目的第一步。

Does anyone know what could be happening? 有人知道会发生什么吗?

Well after a lot of struggle, this was it... 经过很多努力,就是这样...

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

And the preflight class: 和飞行前班:

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

    }

I hope this helps anyone else! 我希望这对其他人有帮助!

405 comes up when your request data type not supported. 不支持您的请求数据类型时,出现405。 You need to pass content type in following 您需要在下面传递内容类型

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

and at API layer 在API层

 public async Task<HttpResponseMessage> Save(UserDto user)

or 要么

 public HttpResponseMessage Save(UserDto user)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM