Есть ли способ использовать логин RestAPI для веб-приложения Asp. net MVC с c# без использования внешнего интерфейса javascript? - PullRequest
0 голосов
/ 28 февраля 2020

У меня есть логин / индексное представление в asp. net mvc views

@{
ViewData["Title"] = "Index or login page";
}

<div class="text-center">
    <label>Email Address</label>
    <input type="email" id="txtemail" placeholder="Enter your email" />

    <br/>

    <label>Password</label>
    <input type="password" id="txtpass" placeholder="Enter your email" />


    <button type="button" id="btnLogin">Login</button>
</div>

У меня есть следующие данные в моем классе модели

namespace test.Models
{
public class Login_Model
{
    public string email { get; set; } //you get to see the user email.
    public string name { get; set; } //user name 
    public Product[] products { get; set; } //list of products
    public string result { get; set; } // success/unsuccess
    public string message { get; set; } 
}
public class Product
{
    public string billingcycle { get; set; }
    public string nextduedate { get; set; }
    public int pid { get; set; }
    public string product_name { get; set; }
    public string product_package { get; set; }
    public string regdate { get; set; }
    public string status { get; set; }
    public string username { get; set; }
}
}

Я сталкиваюсь с проблемой, что с этим классом модели мне дают два параметра "uemail" и "upwd" (которые не представлены в моем классе моделей) для входа в систему и генерации результатов и сведений о продукте. Но когда я передаю свой класс Login_Model в качестве параметра метода [HttpPost] в моем контроллере, я не могу сравнить «uemail» и «upwd» с моим пользовательским вводом.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using test.Models;
using RestSharp;

namespace test.Controllers
{
public class HomeController : Controller
{
    private string baseUrl = "https://webservice.sample.com/";
    private RestClient client;
    private RestRequest Request;
    private IRestResponse response;

    private readonly ILogger<HomeController> _logger;

    public HomeController(ILogger<HomeController> logger)
    {
        _logger = logger;
    }

    public IActionResult Index()
    {
        return View();
    }
    [HttpPost]
    public IActionResult Index(Login_Model login)
    {
         client = new RestClient(baseUrl);
        Request = new RestRequest("login.php", Method.POST);


        return RedirectToAction("Privacy");
    }


    public IActionResult Privacy()
    {
        return View();
    }

    [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
    public IActionResult Error()
    {
        return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
    }
}
}

Что может быть лучший способ получить строку json .result == "success" в asp. net mvc, чтобы перенаправить мое представление индекса в представление конфиденциальности.

1 Ответ

0 голосов
/ 28 февраля 2020

Да. Вы можете использовать класс HttpWebRequest для отдыха вызовов APi

string url = "https://api.xxxxx.com/v1/login/";

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.Headers.Add("API-key", "your-api-key-if-any");
request.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 7.1; Trident/5.0)";
request.Accept = "/";
request.UseDefaultCredentials = true;
request.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;

string postData = "This is a test that posts this string to a Web server.";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);

request.ContentType = "application/x-www-form-urlencoded";
// 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();


HttpWebResponse resp = request.GetResponse() as HttpWebResponse;
using (var streamReader = new StreamReader(resp.GetResponseStream()))
{
    var result = streamReader.ReadToEnd();
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...