简体   繁体   English

RestSharp 不适用于 ASP.NET Core(HTTP POST 方法)

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

Login model code:登录model密码:

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).我正在尝试运行此 controller 方法,但在 ASP.NET Core 上,它不起作用(它不仅在 ASP.NET Core 上起作用,通常代码工作正常)。

The compiler doesn't recognize response.AddParameter , HttpCookie , RestClient , RestRequest etc.编译器无法识别response.AddParameterHttpCookieRestClientRestRequest等。

(generally, this code login to another domain, get the authTokken and save it in the cookies) (一般来说,这段代码登录到另一个域,获取 authTokken 并将其保存在 cookie 中)

Example for an error:错误示例:

The type or namespace name 'RestRequest' could not be found找不到类型或命名空间名称“RestRequest”

How can I modify the code to fix the problems?如何修改代码以解决问题?

Thanks!谢谢!

Don't use AddJsonBody for sending a pre-serialized JSON sting.不要使用AddJsonBody发送预序列化的 JSON 字符串。 It's clearly described in the documentation.它在文档中有清楚的描述

Either send an object with AddJsonBody or use AddStringBody with DataFormat.Json .使用 AddJsonBody 发送AddJsonBody或将AddStringBodyDataFormat.Json一起使用。

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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