简体   繁体   中英

RestSharp doesn't work on ASP.NET Core (HTTP POST method)

Login model code:

namespace Tools.Models
{
    public class Login
    {
        [Required(ErrorMessage = "The username field is required")]
        public string username { get; set; }

        [Required(ErrorMessage = "The password field is required")]
        public string password { get; set; }

        public string LoginUrl { get; set; }
    }
}
public ActionResult SubmitLogin(Login model)
{
    var client = new RestClient(model.LoginUrl);
    var request = new RestRequest(Method.POST);
    var dataToSend = new
        {
            userName = model.UserName,
            password = model.Password,
            reCaptcha = new
            {
                recaptchaResponse = "111",
                isReCaptchaEnabled = false
            }
        };
        
    string jsonToSend = JsonConvert.SerializeObject(dataToSend);
    request.AddParameter("application/json; charset=utf-8", jsonToSend, ParameterType.RequestBody);

    var response = client.Execute(request);

    if (response.IsSuccessful && response.Cookies.Count > 0)
    {
        var cookieName = "AuthToken";
        var authCookie = response.Cookies.FirstOrDefault(cookie => cookie.Name == cookieName);

        if (authCookie != null && !string.IsNullOrEmpty(authCookie.Value))
        {
            // set header
            var cookie = new HttpCookie(cookieName, authCookie.Value);
            cookie.Expires = authCookie.Expires;
            Response.Cookies.Add(cookie);
               
            return Redirect....;
        }
    }
        
    return new EmptyResult();
}

I'm trying to run this controller method but on ASP.NET Core, it doesn't work (it doesn't work only on ASP.NET Core, generally the code is working fine).

The compiler doesn't recognize response.AddParameter , HttpCookie , RestClient , RestRequest etc.

(generally, this code login to another domain, get the authTokken and save it in the cookies)

Example for an error:

The type or namespace name 'RestRequest' could not be found

How can I modify the code to fix the problems?

Thanks!

Don't use AddJsonBody for sending a pre-serialized JSON sting. It's clearly described in the documentation.

Either send an object with AddJsonBody or use AddStringBody with DataFormat.Json .

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM