【问题标题】:Post data from angularjs client to WEBAPI controller将数据从 angularjs 客户端发布到 WEBAPI 控制器
【发布时间】:2016-06-16 07:11:05
【问题描述】:

我是 Angular js 和 webapi 的新手

问题:

我无法使用 json url: "NewRoute/firstCall" 从视图向 WebAPI 控制器发布数据

但我可以使用网址发帖:“http://localhost:2730/NewRoute/firstCall”,

没有http://localhost:2730谁可以发布数据

问题是我在一个解决方案中有两个项目。 1.AngularJS 2.WebAPI

在视图部分

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <script src="Scripts/angular.js"></script>
        <script>     
            var TestCtrl = function ($scope, $http) {
                $scope.SendData = function (Data) {
                    var GetAll = new Object();
                    GetAll.txt1 = Data.txt1;
                    $http({
                        url: "NewRoute/firstCall",
                        //url: "http://localhost:2730/NewRoute/firstCall",
                        dataType: 'json',
                        method: 'POST',
                        data: GetAll,
                        headers: {
                            "Content-Type": "application/json"
                        }
                    }).success(function (response) {
                        $scope.value = response;
                    })
                    .error(function (error) {
                        alert(error);
                    });
                }
            };
            var myApp = angular.module("myApp", []);
            myApp.controller("TestCtrl", TestCtrl);
        </script>
    </head>
    <body ng-app="myApp">
        <div ng-controller="TestCtrl">
            <hr />
            <div>
                Enter text
                <input type="text" placeholder="Enter your name" ng-model="details.txt1">
            </div>
            <hr />
            <input type="button" ng-click="SendData(details)" value="Submit" />
            <hr />
            <h4 style="color:blueviolet">{{value}}</h4>
        </div>
        <hr />
    </body>
</html>

在 Web Api 控制器中

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace WebApplication1.Controllers
{
    [RoutePrefix("NewRoute")]
    public class NewController : ApiController
    {
        public class GetAll
        {
            public string txt1 { get; set; }
        }
        [Route("firstCall")]
        [HttpPost]
        public string firstCall(HttpRequestMessage request,
            [FromBody] GetAll getAll)
        {
            return "Success";
        }
    }
}

WebApi 提供者

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace WebApplication1
{
    public class WebApiApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
        protected void Application_BeginRequest()
        {
            if (Request.Headers.AllKeys.Contains("Origin")
                && Request.HttpMethod == "OPTIONS")
            {
                Response.Flush();
            }
        }
    }
}

Global.asax

<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=301879
  -->
<configuration>
  <appSettings>
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5.1" />
    <httpRuntime targetFramework="4.5.1" />
  </system.web>
  <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>
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="Content-Type" />
        <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
      </customHeaders>
    </httpProtocol>
  </system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

【问题讨论】:

  • 显示您的 WebApi 提供者和 Global.asax
  • 好的,我会用它更新我的问题 WebApi 提供者和 Global.asax

标签: c# angularjs asp.net-mvc-4 asp.net-web-api


【解决方案1】:

问题可能是相对 url,因为当你得到一个完整的 url 时它就可以工作。

试试这个:

   $http({
        url: "/NewRoute/firstCall",
        dataType: 'json',
        method: 'POST',
        data: GetAll,
        headers: {
            "Content-Type": "application/json"
        }
    }).success(function (response) {
        $scope.value = response;
    })
    .error(function (error) {
        alert(error);
    });

注意网址前的/。这将导致浏览器使用 url currentdomain.org/NewRoute/firstCall 发出请求

【讨论】:

    猜你喜欢
    • 2015-11-28
    • 2016-04-17
    • 2015-07-09
    • 2018-12-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-22
    • 2018-02-06
    • 1970-01-01
    相关资源
    最近更新 更多