none
How do I get request parameters using RestSharp to Asp.Net.Core? RRS feed

  • Question

  • The request (in a WPF Net.Fx.4 project)

               var client = new RestClient(_serviceAddress);
    
                var request = new RestRequest("SignIn", Method.POST);
    
                request.RequestFormat = DataFormat.Json;
                request.AddJsonBody(new { UserName = userName, Password = password });
                //request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
                var response = client.Execute(request);

    My Api (in a Asp.Net.Core.2.2 project)

            public JsonResult SignIn([FromBody]string UserName, [FromBody]string Password)
            {
                return new JsonResult(new { result = "fail", message = "hello"});//this gets called but params always null
            }
    

    In my API, which does get invoked, the values are always `null`, what am I doing wrong?
     
       https://localhost:44372/api/signin

    I've tried all manner of decorations on the parameters and even none.

    I've also tried various connotations on the `request.Add...` I've tried `AddXmlBody` I've tried adding a header `ContentType` nothing works. I've tried loads of exampled from here and still no joy.

    If I am doing this wrong do please let me know, thanks :)

    DJack10


    • Edited by j4ck50nD Friday, December 6, 2019 9:11 AM
    Friday, December 6, 2019 9:09 AM

Answers

  • Myself, I use the DTO pattern that is known by the WebAPI client and the WebAPI service in passing data between the two. I also use HTTPClinet() that is the defacto.

    https://en.wikipedia.org/wiki/Data_transfer_object

    https://www.codeproject.com/Articles/1050468/Data-Transfer-Object-Design-Pattern-in-Csharp

    https://docs.microsoft.com/en-us/aspnet/web-api/overview/data/using-web-api-with-entity-framework/part-5

    Example where the ASP.NET Core MVC project , that you don't see code, calls methods on the Service object in the ServiceLayer on the client-side that in turn makes calls to the WebAPI that calls the DataAcessLayer  object Data Access Object (DAO) that is doing CRUD with the database that is using EF. The DTO travels between the layers on the client side that eventually are sent/received using the WebAPI using the DAL. 

    BTW, ASP.NET Core and WebAPI have forums in ASP.NET forums.

    http://forums.asp.net/

    using System;
    using System.Collections.Generic;
    using System.Net.Http;
    using System.Net.Http.Headers;
    using System.Text;
    using Entities;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Linq;
    
    namespace ServiceLayer
    {
        public class AuthorSvc :IAuthorSvc
        {
            public List<DtoAuthor> GetAll()
            {
                var dtoauthors = new List<DtoAuthor>();
    
                using (var client = new HttpClient())
                {
                    var uri = new Uri("http://localhost/WebAPI/api/author/GetAll");
    
                    var response = client.GetAsync(uri).Result;
    
                    if (!response.IsSuccessStatusCode)
                        throw new Exception(response.ToString());
    
                    var responseContent = response.Content;
                    var responseString = responseContent.ReadAsStringAsync().Result;
    
                    dynamic authors = JArray.Parse(responseString) as JArray;
    
                    foreach (var obj in authors)
                    {
                        DtoAuthor dto = obj.ToObject<DtoAuthor>();
    
                        dtoauthors.Add(dto);
                    }
                }
    
                return dtoauthors;
            }
            public List<DtoAuthorType> GetAuthorTypes()
            {
                var dtoauthortypes = new List<DtoAuthorType>();
    
                using (var client = new HttpClient())
                {
                    var uri = new Uri("http://localhost/WebAPI/api/author/GetAuthorTypes");
    
                    var response = client.GetAsync(uri).Result;
    
                    if (!response.IsSuccessStatusCode)
                        throw new Exception(response.ToString());
    
                    var responseContent = response.Content;
                    var responseString = responseContent.ReadAsStringAsync().Result;
    
                    dynamic authortypes = JArray.Parse(responseString) as JArray;
    
                    foreach (var obj in authortypes)
                    {
                        DtoAuthorType dto = obj.ToObject<DtoAuthorType>();
    
                        dtoauthortypes.Add(dto);
                    }
                }
    
                return dtoauthortypes;
            }
    
            public DtoAuthor  Find(int id)
            {
                DtoAuthor dto;
    
                using (var client = new HttpClient())
                {
                    var uri = new Uri("http://localhost/WebAPI/api/author/Find?id=" + id);
                    HttpResponseMessage getResponseMessage = client.GetAsync(uri).Result;
    
                    if (!getResponseMessage.IsSuccessStatusCode)
                        throw new Exception(getResponseMessage.ToString());
    
                    var responsemessage = getResponseMessage.Content.ReadAsStringAsync().Result;
    
                    dynamic author = JsonConvert.DeserializeObject(responsemessage);
    
                    dto = author.ToObject<DtoAuthor>();
                }
    
                return dto;
            }
    
            public void Add(DtoAuthor dto)
            {
                using (var client = new HttpClient { BaseAddress = new Uri("http://localhost") })
                {
                    string serailizeddto = JsonConvert.SerializeObject(dto);
    
                    var inputMessage = new HttpRequestMessage
                    {
                        Content = new StringContent(serailizeddto, Encoding.UTF8, "application/json")
                    };
    
                    inputMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    
                    HttpResponseMessage message =
                        client.PostAsync("WebAPI/api/author/Add", inputMessage.Content).Result;
    
                    if (!message.IsSuccessStatusCode)
                        throw new Exception(message.ToString());
                }
            }
    
            public void Update(DtoAuthor dto)
            {
                using (var client = new HttpClient { BaseAddress = new Uri("http://localhost") })
                {
                    string serailizeddto = JsonConvert.SerializeObject(dto);
    
                    var inputMessage = new HttpRequestMessage
                    {
                        Content = new StringContent(serailizeddto, Encoding.UTF8, "application/json")
                    };
    
                    inputMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    
                    HttpResponseMessage message =
                        client.PostAsync("WebAPI/api/author/Update", inputMessage.Content).Result;
    
                    if (!message.IsSuccessStatusCode)
                        throw new Exception(message.ToString());
                }
            }
    
            public void Delete(DtoId dto)
            {
                using (var client = new HttpClient { BaseAddress = new Uri("http://localhost") })
                {
                    string serailizeddto = JsonConvert.SerializeObject(dto);
    
                    var inputMessage = new HttpRequestMessage
                    {
                        Content = new StringContent(serailizeddto, Encoding.UTF8, "application/json")
                    };
    
                    inputMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    
                    HttpResponseMessage message =
                        client.PostAsync("WebAPI/api/author/Delete", inputMessage.Content).Result;
    
                    if (!message.IsSuccessStatusCode)
                        throw new Exception(message.ToString());
                }
            }
        }
    }
    

    using System.Collections.Generic;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Mvc;
    using Entities;
    using DAL;
    
    namespace WebAPI.Controllers
    {
        [Produces("application/json")]
        [Route("api/[controller]")]
        [ApiController]
        public class AuthorController : ControllerBase
        {
            private IDaoAuthor dao;
            public AuthorController(IDaoAuthor daoAuthor)
            {
                dao = daoAuthor;
            }
    
            [HttpGet]
            [Route("GetAll")]
            public async Task<List<DtoAuthor>> GetAll()
            {
                return  await dao.GetAll();
            }
    
            [HttpGet]
            [Route("GetAuthorTypes")]
            public async Task<List<DtoAuthorType>> GetAuthorTypes()
            {
                return await dao.GetAuthorTypes();
            }
    
            [HttpGet]
            [Route("Find")]
            public async Task<DtoAuthor> Find(int id)
            {
                return await dao.Find(id);
            }
    
            [HttpPost]
            [Route("Add")]
            public async Task Add(DtoAuthor dto)
            {
                 await dao.Add(dto);
            }
    
            [HttpPost]
            [Route("Update")]
            public async Task Update(DtoAuthor dto)
            {
                await dao.Update(dto);
            }
    
            [HttpPost]
            [Route("Delete")]
            public async Task Delete(DtoId dto)
            {
                await dao.Delete(dto.Id);
            }
        }
    }

    namespace Entities
    {
        public class DtoAuthor
        {
            public int AuthorId { get; set; }
            public string FirstName { get; set; }
            public string LastName { get; set; }
        }
    }
    

     
    • Marked as answer by j4ck50nD Saturday, December 7, 2019 4:25 PM
    Friday, December 6, 2019 9:42 AM