簡體   English   中英

將數據從angularjs客戶端發布到WEBAPI控制器

[英]Post data from angularjs client to WEBAPI controller

我是angular js和webapi的新手

問題:

我無法使用json url:“ NewRoute / firstCall”將數據從視圖發布到WebAPI控制器

但我可以使用url發布:“ 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>

可能是相對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發出請求

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM