2016-07-28 33 views
2

Ich habe ein Problem und obwohl ich viele Antworten auf das gleiche Thema gesehen habe, hat nichts wirklich funktioniert .. Ich habe ein WebAPI-Projekt und ein MVC, wo ich Angular habe.WebApi + AngularJS: 405 Methode nicht erlaubt

Vom Angular Projekt, ich versuche, so etwas zu schreiben:

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; 

Wenn Sie sehen, ich bin die gleiche API zweimal im Fall ruft es ist eine Angular Sache, aber für mich ist es nicht ..

ich habe diesen Controller in meinem API Projekt:

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

Dies ist die Antwort, die ich habe:

Response

Und das ist mein 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 Mein WebApiConfig sieht wie folgt aus:

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

schließlich das einzige, was "weird" ist, dass ich mit IISExpress wie dies sind die ersten Schritte meines Projekts ..

Hat jemand Wissen Sie, was passieren könnte?

+0

Wie sieht Ihre 'Register' Methode in' WebApiConfig.cs' aus? Außerdem würde ich als allgemeinen Ratschlag vermeiden, Routenpräfixe zu erstellen, die nicht mit Ihren Controller-Namen übereinstimmen. Wenn Ihr Projekt wächst, wird es immer frustrierender, in Ihrem Code zu navigieren, wenn der Name des Controllers nicht mit dem Routenpräfix übereinstimmt. Mehr noch, wenn Sie in einem Team arbeiten. – Lex

+0

Dort habe ich es hinzugefügt .. Sie haben einen Punkt, aber ehrlich gesagt ist es nur ein Test-Controller, um die Cross-Domain-Sache Arbeit zu bekommen. –

Antwort

1

Nun nach viel Kampf, das war es ...

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

Und die Preflight-Klasse:

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

    } 

Ich hoffe, das hilft jedem anderen!

0

405 wird angezeigt, wenn Ihr Anfragedatentyp nicht unterstützt wird. Sie müssen in

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

und API-Schicht

public async Task<HttpResponseMessage> Save(UserDto user) 
folgenden Inhaltstyp übergeben

oder

public HttpResponseMessage Save(UserDto user) 
+0

Ich habe ein anderes Projekt mit API und Angular arbeiten und ich musste das alles nicht tun. In der Tat ist das der Grund, warum dieser Fehler für mich so komisch ist. –