【问题标题】:How to post JSON data from ASP.Net MVC controller?如何从 ASP.Net MVC 控制器发布 JSON 数据?
【发布时间】:2016-03-08 10:36:28
【问题描述】:

我正在构建一个 ASP.Net MVC Web 应用程序,它将成为安全设备的门户。本设备支持 JSON API。我尝试开发客户端(使用 $httpProvider 方法发布和获取数据的 angularJS 脚本)但陷入了 CORS 的问题。

我想要做的是:网络应用服务器将发布并获取请求,然后将它们作为简单的 HTML 重定向到客户端。

问题是如何从我的控制器向这个设备执行 HTTP 请求。

这个question有一个不清楚的答案。

请注意,我尝试在控制器中使用 HTTPWebRequest,但命名空间 System.Net.HTTP.WebRequest 不会被包括在内,即使它在我的项目的引用中。

编辑: 目前的尝试: 这是帐户模型:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Globalization;
using System.Web.Security;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

namespace Project1.Models
{
    public class LoginModel
    {
        [Required]
        [Display(Name = "User name")]
        public string UserName { get; set; }

        [Required]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { get; set; }




        internal System.Web.Mvc.ActionResult PostJson(LoginModel model, StringContent query)
        {
            throw new NotImplementedException();
        }
    }
}

这是控制器:

    using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Transactions;
using System.Web;
using System.Web.Mvc;
using Newtonsoft;
using System.Web.Security;
using DotNetOpenAuth.AspNet;
using System.Net.Http;
using System.Net.Http.Headers;
using Microsoft.Web.WebPages.OAuth;
using WebMatrix.WebData;
using Project1.Models;

namespace Project1.Controllers
{
    [Authorize]
    public class AccountController : Controller
    {
        public async Task<ActionResult> PostJson(LoginModel model, StringContent data)
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("http://localhost:1532/Account/Login");
                HttpResponseMessage response = await client.PostAsync("http://192.168.30.1/jsonrpc", data);
                if (response.IsSuccessStatusCode)
                {
                    Console.Write(response.ToString());

                }
                Console.Write(response.ToString());
                return View(model);

            }
        }

        //
        // GET: /Account/Login

        [AllowAnonymous]
        public ActionResult Login(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            return View();
        }

        //
        // POST: /Account/Login

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Login(LoginModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                var data ="{\"params\" : [{\"url\" : \"sys/login/user\",\"data\" : [{\"passwd\" :" + model.Password +",​\"user\" :" + model.UserName + "}]}],\"session\" : 1,\"id\" : 1,\"method\" : \"exec\"}";
                StringContent query = new StringContent(data);
                return (model.PostJson(model,query));
            }

            // If we got this far, something failed, redisplay form
            ModelState.AddModelError("", "The user name or password provided is incorrect.");
            return View(model);
        }


        #region Helpers
        private ActionResult RedirectToLocal(string returnUrl)
        {
            if (Url.IsLocalUrl(returnUrl))
            {
                return Redirect(returnUrl);
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }
        }
        #endregion
    }
}

【问题讨论】:

  • 你应该看看httpclient
  • @CallumLinington 这似乎可行。问题是在 HttpClient 中使用 POST 和 GET 会导致一些问题,因为 post 和 get 是异步的,而控制器是同步的。
  • 控制器动作可以是异步的
  • 您有两个选择,public async Task&lt;IActionResult&gt; SomeAction() 作为您的控制器操作,或者您可以执行 client.PostAsync().Result
  • @CallumLinington 这引发了NotImplementedException 出于某种我无法理解的原因。

标签: c# asp.net json asp.net-mvc


【解决方案1】:

使用PostMan 发送 JSON 后,我能够为 JSON 请求和响应创建类。接下来我要做的就是添加一个名为Service 的类。在这个具有整数和 JSON 服务器的 url 作为属性的类中,我添加了所有函数来调用 API。整数代表请求的ID,每个函数都会用到url。

现在这才是真正重要的。 以下代码用于使用来自远程设备的凭据进行登录并以 JSON 数据发送用户输入:

public Response Login(String usr, String pwd)
        {
            this.MyId++;
            Request model = new Request(id, usr, pwd);
            var http = (HttpWebRequest)WebRequest.Create(uri);
            http.Accept = "application/json";
            http.ContentType = "application/json";
            http.Method = "POST";
            String json = Newtonsoft.Json.JsonConvert.SerializeObject(model);
            UTF8Encoding encoding = new UTF8Encoding();
            Byte[] bytes = encoding.GetBytes(json);

            Stream newStream = http.GetRequestStream();
            newStream.Write(bytes, 0, bytes.Length);
            newStream.Close();

            var response = http.GetResponse();

            var stream = response.GetResponseStream();
            var sr = new StreamReader(stream);
            var content = sr.ReadToEnd();
            Response res= Newtonsoft.Json.JsonConvert.DeserializeObject<Response>(content.ToString());
            return res;

        }

正如您在此处所注意到的,我们创建了一个名为 Request 的 c# 类的实例。然后将此类序列化为 JSON 字符串。然后将 JSON 字符串放入流中并使用UTF-8 Encoding 发送。然后我们得到响应并将其反序列化为c# 类,通过它我们可以知道用户是否经过身份验证。根据结果​​,我们可以将客户端重定向到他的主页或提示他输入正确的登录名和密码。

PS 这个程序是完全免费的CORS。通过这种方式,我在服务器中发送和接收数据并对其进行评估,然后相应地发送HTML 视图。这使我的请求和远程设备完全隐藏。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-11
    • 2018-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多