简体   繁体   English

AngularJS,REST,C#Service,405 - 不允许发布方法

[英]AngularJS , REST, C# Service, 405 - Post Method Not Allowed

I'm trying to do a full Angularjs web site for training. 我正在尝试完整的Angularjs网站进行培训。 I've read many articles about this Method not allowed , but didn't find a solution. 我已经阅读了很多关于此方法的文章,但是没有找到解决方案。 I'm trying to send a data object to my service. 我正在尝试将数据对象发送到我的服务。

Error : Failed to load resource: the server responded with a status of 405 (Method Not Allowed) 错误:无法加载资源:服务器响应状态为405(方法不允许)

Here is my AngularJS Part. 这是我的AngularJS Part。

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

Here's my service part 这是我的服务部分

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

WebConfig Comming WebConfig Comming

<?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>

And at least , the CORS 至少,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);
            }
        }
    }

Can you help me? 你能帮助我吗?

In advance, thanks! 提前谢谢! :) :)

网络选项卡 错误列表

Try one of the following 请尝试以下方法之一

  • Define a another WebInvoke method with Method="OPTIONS" , the method should return empty content , since your CORS behavior handler adds all pre-flight headers needed for your browser . 使用Method =“OPTIONS”定义另一个WebInvoke方法,该方法应返回空内容,因为您的CORS行为处理程序会添加浏览器所需的所有飞行前标题。
  • Your CORS Extension should analyze the current request METHOD if it is OPTIONS it should short-circuit and return empty content with the pre-flight headers. 你的CORS扩展应该分析当前的请求METHOD,如果它是OPTIONS它应该短路并返回带有飞行前标题的空内容。 If the method type is "GET"/"POST" it should let the request through to be processed by the endpoint. 如果方法类型是“GET”/“POST”,它应该让请求通过端点处理。

The browser makes two request one to get pre-flight info using options and another for the actual api call . 浏览器使用两个请求来获取使用选项的飞行前信息,使用另一个请求获得实际的api呼叫。

the problem you are having is the first call by the browser Method=OPTIONS is being rejected by your endpoint. 您遇到的问题是浏览器第一次调用方法= OPTIONS被您的端点拒绝。 because it can only process POST. 因为它只能处理POST。

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

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