2017-03-23 61 views
1

我正在尝试做一个完整的Angularjs网站进行培训。我读过很多关于这个的文章不允许的方法,但是没有找到解决办法。我试图发送一个数据对象到我的服务。AngularJS,REST,C#服务,405 - 不允许Post方法

错误:无法加载资源:服务器与405状态响应(不允许的方法)

这是我AngularJS部分。

var addNews = 
     { 
      Title: newsList.newsTitle, 
      NewsContent: newsList.newsContent, 
      CreationDate: newsList.newsCreationDate, 
      CreatedBy: newsList.newsAuthor, 
      ModificationDate: newsList.newsCreationDate, 
      ModifiedBy: newsList.newsAuthor 
     }; 

    var news = JSON.stringify(addNews); 


    $http({ 
     method: 'POST', 
     dataType: 'json', 
     url: 'http://localhost:11672/InfinytecServices.svc/SaveNews', 
     headers: { 
      'Content-Type': 'application/json', 
      'Accept': 'application/json' 
     }, 
     data: news 
    }); 

这里是我的服务部分

[OperationContract] 
    [WebInvoke(Method = "POST", 
     UriTemplate = "/SaveNews", 
     RequestFormat = WebMessageFormat.Json, 
     ResponseFormat = WebMessageFormat.Json)] 
    int SaveNews(News news); 

WebConfig正在添加

<?xml version="1.0" encoding="utf-8"?> 
<configuration> 

    <appSettings> 
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" /> 
    </appSettings> 

    <system.web> 
    <compilation debug="true" targetFramework="4.6.1" /> 
    <httpRuntime targetFramework="4.6.1"/> 
    </system.web> 

    <system.serviceModel> 
    <protocolMapping> 
     <add binding="webHttpBinding" scheme="http" /> 
    </protocolMapping> 

    <extensions> 
     <behaviorExtensions> 
     <add 
      name="crossOriginResourceSharingBehavior" 
      type="InfinytecWebService.CORSEnablingBehavior, InfinytecWebService, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"/> 
     </behaviorExtensions> 
    </extensions> 

    <behaviors> 
     <serviceBehaviors> 
     <behavior name="serviceBehavior"> 
      <serviceMetadata httpGetEnabled="true" httpsGetEnabled="false"/> 
      <serviceDebug includeExceptionDetailInFaults="true"/> 
     </behavior> 
     </serviceBehaviors> 
     <endpointBehaviors> 
     <behavior name="web"> 
      <webHttp/> 
      <crossOriginResourceSharingBehavior /> 
     </behavior> 
     </endpointBehaviors> 
    </behaviors> 

    <services> 
     <service behaviorConfiguration="serviceBehavior" name="InfinytecWebService.InfinytecServices"> 
     <endpoint address="" 
        behaviorConfiguration="web" 
        binding="webHttpBinding" 
        contract="InfinytecWebService.IInfinytecServices" /> 
     </service> 
    </services> 

    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" /> 

    </system.serviceModel> 

    <system.webServer> 
    <modules runAllManagedModulesForAllRequests="true"/> 
    <directoryBrowse enabled="true"/> 
    </system.webServer> 

</configuration> 

而且至少,在CORS

public class CORSEnablingBehavior : BehaviorExtensionElement, IEndpointBehavior 

    { 
     public void AddBindingParameters(
      ServiceEndpoint endpoint, 
      BindingParameterCollection bindingParameters){ } 

     public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime) { } 

     public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher) 
     { 
      endpointDispatcher.DispatchRuntime.MessageInspectors.Add(
       new CORSHeaderInjectingMessageInspector() 
      ); 
     } 

     public void Validate(ServiceEndpoint endpoint) { } 

     public override Type BehaviorType { get { return typeof(CORSEnablingBehavior); } } 

     protected override object CreateBehavior() { return new CORSEnablingBehavior(); } 

     private class CORSHeaderInjectingMessageInspector : IDispatchMessageInspector 
     { 
      public object AfterReceiveRequest(
       ref Message request, 
       IClientChannel channel, 
       InstanceContext instanceContext) 
      { 
       return null; 
      } 
      private static IDictionary<string, string> _headersToInject = new Dictionary<string, string> 
      { 
      { "Access-Control-Allow-Origin", "*" }, 
      { "Access-Control-Request-Method", "POST,GET,PUT,DELETE,OPTIONS" }, 
      { "Access-Control-Allow-Headers", "X-Requested-With,Content-Type" } 
      }; 
      public void BeforeSendReply(ref Message reply, object correlationState) 
      { 
       var httpHeader = reply.Properties["httpResponse"] as HttpResponseMessageProperty; 
       foreach (var item in _headersToInject) 
        httpHeader.Headers.Add(item.Key, item.Value); 
      } 
     } 
    } 

你能帮助我吗?

提前,谢谢! :)

Network Tab List of errors

+1

您可以发布浏览器网络选项卡的屏幕截图吗?浏览器使用OPTIONS进行两个调用,另一个使用POST方法。当你的服务通过OPTIONS方法接收到请求时,它应该返回CORS信息,并在它到达你的api方法之前结束请求。由于api只接受POST,所以无法处理OPTIONS请求。 –

+0

在帖子中添加,我还添加了控制台选项卡。 Thx :) – Eidan

回答

0

尝试以下

  • 一个定义一个又一个WebInvoke方法与方法= “OPTIONS”,该方法应该返回空的内容,因为你的行为CORS处理器将所有您的浏览器需要使用飞行前头文件。
  • 您的CORS扩展应该分析当前的请求方法,如果它是OPTIONS它应该短路并返回空的内容与飞行前报头。如果方法类型是“GET”/“POST”,它应该让请求通过端点进行处理。

浏览器发出两个请求,一个使用选项获取飞行前信息,另一个用于实际api调用。

您遇到的问题是浏览器的第一个调用Method = OPTIONS被您的端点拒绝。因为它只能处理POST。