从C#应用程序向Angular页面发送帖子请求

Send post request to Angular page from C# app

本文关键字:请求 应用程序 Angular      更新时间:2023-09-26

我知道如何将带有angular的post请求发送到API,但不知道如何检索从应用程序发送的post要求。

假设我有这个C#帖子请求:

    public string sendPost(string data)
    {
        // Create a request using a URL that can receive a post. 
        WebRequest request = WebRequest.Create("http://localhost:5000/app/edit");
        // Set the Method property of the request to POST.
        request.Method = "POST";
        // Create POST data and convert it to a byte array.
        string postData = "{'"data'":'"" + data + "'"}";
        byte[] byteArray = Encoding.UTF8.GetBytes(postData);
        // Set the ContentType property of the WebRequest.
        request.ContentType = "application/json";
        // Set the ContentLength property of the WebRequest.
        request.ContentLength = byteArray.Length;
        // Get the request stream.
        Stream dataStream = request.GetRequestStream();
        // Write the data to the request stream.
        dataStream.Write(byteArray, 0, byteArray.Length);
        // Close the Stream object.
        dataStream.Close();
        // Get the response.
        WebResponse response = request.GetResponse();
        // Display the status.
        Console.WriteLine(((HttpWebResponse)response).StatusDescription);
        // Get the stream containing content returned by the server.
        dataStream = response.GetResponseStream();
        // Open the stream using a StreamReader for easy access.
        StreamReader reader = new StreamReader(dataStream);
        // Read the content.
        string responseFromServer = reader.ReadToEnd();
        // Display the content.
        Console.WriteLine(responseFromServer);
        // Clean up the streams.
        reader.Close();
        dataStream.Close();
        response.Close();
        return responseFromServer;
    }

在我的angular应用程序中,我有一个控制器:

(function () {
    'use strict';
    angular.module('anbud')
      .controller('editController', ['$scope', 'localStorage', 'md5', '$routeParams', 'httpError',
          function ($scope, localStorage, md5, $routeParams, httpError) {
              function processHeaderData() {
                  console.log($routeParams.json);
              }
              processHeaderData();
          }]);
}());

我可以通过url发送数据并使用routeParams,但我想使用POST。如何访问POST数据?

我认为您混淆了前端和web服务器技术。

Angular是一种前端技术,向Angular发送帖子实际上意味着向托管Angular网站的web服务器发送请求。

一旦你弄清楚了这一点,你只需要像处理angular一样向web服务器发送一个API调用,服务器就会返回你需要的json数据。

如果你想获得特定路由的HTML表示,恐怕没有什么好的方法可以实现。angular也不例外,任何使用ajax调用加载数据的站点都会遇到这个问题。

Angular$http.post也可以检索数据。出于安全目的,这是非常有益的。其逻辑保持不变。

您可以通过以下方式从c#控制器发送数据:

using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace Sample.API.Controllers
{
    public class ContentDataController
    {
        [Route("api/ContentData")]
        [HttpPost]
        public HttpResponseMessage SamplePost(SampleRequest request)
        {
            HttpResponseMessage response;
            try
            {
                var cda = dataContentAdapter(); 
                //Business logic here
                var result = cda.GetContent(request);
                //pass the above result to angular
                response = Request.CreateResponse(HttpStatusCode.OK, result);
                response.Content.Headers.Expires = new DateTimeOffset(DateTime.Now.AddSeconds(300));
            }
            catch (Exception ex)
            {
                ApplicationLogger.LogCompleteException(ex, "ContentDataController", "Post");
                HttpError myCustomError = new HttpError(ex.Message) { { "IsSuccess", false } };
                return Request.CreateErrorResponse(HttpStatusCode.OK, myCustomError);
            }
            return response;
        }
    }
}

这样,就可以从angular发送一个请求,其中包含请求中需要使用的任何数据。最好是发送json,解析业务逻辑中的json。

为angular$http创建一个具有新有效负载的HttpResponseMessage以接收。