将数据从angularjs客户端发布到WEBAPI控制器

时间:2016-06-16 07:11:06

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

我是角度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>

1 个答案:

答案 0 :(得分:0)

这可能是问题的相对网址,因为当你有一个完整的网址时,它会正常工作。

试试这个:

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

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

发出请求