Get json data from POST method in asp.net mvc - c#

I got an error while getting json data from POST method, am I doing something wrong
C# Code:
public IActionResult signupapi(UserSignUp user)
{
var model = new Models.SignUpModelAPI(HttpContext);
if (user == null)
{
return Content(model.ResponseJsonText(false, string.Format(model.Language("empty"),
HttpContext.Request.Method, HttpContext.Request.Path.Value), Class.CodeResponse.ERROR), new Microsoft.Net.Http.Headers.MediaTypeHeaderValue("application/json"));
}
if (!model.isAllowMethod("POST"))
{
return Content(model.ResponseJsonText(false,string.Format(model.Language("notallowmethod"),
HttpContext.Request.Method,HttpContext.Request.Path.Value),Class.CodeResponse.ERROR),new Microsoft.Net.Http.Headers.MediaTypeHeaderValue("application/json"));
}
return Content(JsonConvert.SerializeObject(user));
}
public class UserSignUp
{
public string fullname { get; set; }
public string username { get; set; }
public string email { get; set; }
public string password { get; set; }
}
And this is the result when i try on reqbin every value i get is null

You need to add FromBody attribute to get your data for the POST operation:
public IActionResult signupapi([FromBody]UserSignUp user)
You can read more on parameter binding on MSDN docs.

Related

pass model data between razor pages

I try pass model data between two Razor pages, data is not string or bool or int
data that i want pass to second page is a model,
i do taht with this way,
public class AskLibrarian
{
public int Id { get; set; }
public string FullName { get; set; }
public string Subject { get; set; }
public string Email { get; set; }
public string Text { get; set; }
public string UserIp { get; set; }
public DateTime CreateDate { get; set; }
public bool ReadIt { get; set; }
public bool Answer { get; set; }
public string reciptCode { get; set; }
}
And on Get method pass data with this way:
[BindProperty]
public AskLibrarian AskLibrarian { get; set; }
public async Task<IActionResult> OnPostQuestionAsync()
{
if (!ModelState.IsValid)
{
return Page();
}
AskLibrarian.Answer = false;
AskLibrarian.CreateDate = DateTime.Now;
AskLibrarian.ReadIt = false;
string userIp = $"{ HttpContext.Connection.RemoteIpAddress}";
if (string.IsNullOrEmpty(userIp))
{
userIp = "127.0.0.1";
}
AskLibrarian.UserIp = userIp;
string rndNuber = Business.RandomNumberForQuestion.randCode;
AskLibrarian.reciptCode = rndNuber;
await _emailSenderService.SendEmailAsync(AskLibrarian.Email, AskLibrarian.FullName, rndNuber);
_context.AskLibrarians.Add(AskLibrarian);
await _context.SaveChangesAsync();
Message = "your message sended";
//return RedirectToPage("/Subfolder/Index", new { SFId = 7 });
return RedirectToPage("/Subfolder/AskLibrarianCode", new { asklib = AskLibrarian });
}
In post method in second page, like to get data on this way:
public void OnGet(Model.AskLibrarian asklib)
{
askLibrarianVM = new AskLibrarianVM
{
Answered = false,
CreateDate = asklib.CreateDate,
LastUpdate = asklib.CreateDate,
RandomeCode = asklib.reciptCode,
Status = false,
};
}
But asklib is empty ,I set a breakpoint at end of Get method and I sow that asklib if filled with valid values but in post method when i try to get data, asklib is empty
what is my mistake
The simple answer was :
return RedirectToPage("/Subfolder/AskLibrarianCode", AskLibrarian );
My mistake was
... new{asklib = AskLibrarian});
After more than two hours
The lowest friction way is to return View("SomeViewForTheModel", AskLibrarian) and do your thing with a completely different view. Your second page controller action really isn't doing anything.
Otherwise, you'll have to save the ID associated with your AskLibrarian object, presumably in a database, and then look it up on the second page either by putting the ID in the URL path (be sure to validate the user should see it!), or by looking up in the database whatever is owned by the user.

How to redirect to an url which is coming from the database in .NET?

I have a web api built in .NET, within an endpoint i would like to redirect to an url which matches the the code inserted in database. the endpoint takes as entry the code and i am supposed to redirect to the corresponding url. For that i use the Redirect method which actually is not working. i did Console.Write to print if the url is null or empty but it exists. here is the code of my controller :
[HttpGet("{hash}")]
// [ProducesResponseType(302)]
//[ProducesResponseType(404)]
public async Task<IActionResult> redirectUrl(string hash)
{
var t = await new ServiceUrl(_ctx).GetTarget2(hash);
int a = 0;
foreach (Model.Data.DAO.Url i in t)
{
if (i != null)
{
a=a+1;
}
}
if (a==0)
{
return new TimeoutExceptionObjectResult(error: "Not Found",503);
}else
if (DateTime.Compare(DateTime.Now, t.ElementAt(0).ExpireAt) > 0)
{
t.ElementAt(0).state = "expire";
_ctx.Entry(t.ElementAt(0)).State = EntityState.Modified;
await _ctx.SaveChangesAsync();
return new TimeoutExceptionObjectResult(error: "Url expiré",501);
}
string url= t.ElementAt(0).UrlOrigin;
Console.Write(url);
return new Redirect(url);
}
the GetTarget2 method :
public async Task<IEnumerable<Url>> GetTarget2(string hash)
{
var t2 = await _ctx.Url.Where(u => u.UrlShort == hash).ToArrayAsync();
return t2;
}
and the entity :
[Table("Url")]
public class Url
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string UrlShort { get; set; }
public string UrlOrigin { get; set; }
public string state { get; set; }
public int Customer_id { get; set; }
public int? targetItemId { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime ExpireAt { get; set; }
[JsonIgnore]
public List<Stats> GetStats { get; set; }
public Url()
{
}
public Url(int Id,string UrlShort,string UrlOrigin,string state,int Customer_id,DateTime CreatedAt,DateTime ExpireAt)
{
this.Id = Id;
this.UrlShort = UrlShort;
this.UrlOrigin = UrlOrigin;
this.state = state;
this.Customer_id = Customer_id;
this.CreatedAt = CreatedAt;
this.ExpireAt = ExpireAt;
}
}
when i try to pass a code which is in database i get this : Not found which means it does not find it in database
Update:
the database context declaration :
private readonly DatabaseContext _ctx;
and its definition :
public class DatabaseContext : DbContext
{
public DatabaseContext(DbContextOptions<DatabaseContext> options) : base(options)
{
}
public DbSet<Url> Url { get; set; }
public DbSet<User> User { get; set; }
public DbSet<Stats> Stats { get; set; }
}
If I understood your question correctly then you are trying to redirect to another action method by reading the URL from the database. If the retured Url belongs to your application and just have the dynamic parameter then you can try RedirectToAction method for the redirect.
Syntax:
return RedirectToAction("ActionName", new { id = 90 });
The will cause a redirect to YourApp/Controller/ActionName/90
All you have to create an action method with argument (if required) and redirect from another action method from where you are getting url.
Alternativly you can also use
return RedirectToAction("Index", new RouteValueDictionary(
new { controller = "NameOfController", action = "Index", id = id } )
);
The problem was the Redirect method which indicates its content was null or empty although i printed the url in terminal successfully. So What i did is adding a prefix (http://) like this Redirect("http://"+url), url is the url coming from the database. if the url already contains the prefix http or https i remove it before passing it as parameter inside Redirect method. Doing this solved my problem.

How to correctly pass a string id to API controller in Xamarin.Forms

I'm writing a mobile app using Xamarin Forms where I am going to consume an REST API.
At the moment, I have a user model
{
public string UserId { get; set; }
public string UserDisplayName { get; set; }
public int UserRoleId { get; set; }
public string UserFirstName { get; set; }
public string UserLastName { get; set; }
public string UserEmail { get; set; }
public string UserPostcode { get; set; }
public DateTime UserCreatedAt { get; set; }
public DateTime UserModifiedAt { get; set; }
public bool UserDeletedAt { get; set; }
}
And I have defined a GetUser method on my controller
// GET: api/Users/5
[HttpGet("{id}")]
public async Task<ActionResult<User>> GetUser(string id)
{
var user = await _context.User.FindAsync(id);
if (user == null)
{
return NotFound();
}
return user;
}
If I test the API using Postman and parse the string id without quotes(edit) on the route, it works fine. E.g. https://localhost:5051/api/Users/Example. However, if I parse the id within qutoes(edit) it doesn't work: https://localhost:5051/api/Users/"Example"
My problem is, on my mobile client, when it calls the web service that calls the API, it needs to parse a string, which goes with the quotes(edit)- matching the second example.
Does any of you know a solution or a workaround for this?
Thanks in advance
EDIT:
My service method is as follows
public static async Task<IEnumerable<User>> GetUserById(string id)
{
var json = await client.GetStringAsync($"api/users/{id}");
var users = JsonConvert.DeserializeObject<IEnumerable<User>>(json);
return users;
}
And my service call is
var users = await UserService.GetUserById("Example");
EDIT2: Fixed
Service method changed to
public static async Task<User> GetUserById(string id)
{
var json = await client.GetStringAsync($"api/users/{id}");
var users = JsonConvert.DeserializeObject<User>(json);
return users;
}
It turns out the issue was caused by the IEnumerable type on the task definition, which makes sense since I was trying to retrieve a single instance.
Service method changed to
public static async Task<User> GetUserById(string id)
{
var json = await client.GetStringAsync($"api/users/{id}");
var users = JsonConvert.DeserializeObject<User>(json);
return users;
}

How to retrieve incoming parameters using C#?

I am integrating with waboxapp API (link) using ASP.NET Core MVC 2.0.
Some parameters have been posted like this
contact[uid], contact[name], contact[type], message[uid], message[body] etc...
I have tried the following code :
[HttpPost]
public IActionResult Index(string uid, string token, List<string> contact)
{
foreach (string item in contact) {
Common.TestEmail(uid, token);
}
return View();
}
What is the proper way to retrieve incoming parameters?
For waboxapp, its request is Standard HTTP format (application/x-www-form-urlencoded). Try to follow steps below:
Model
public class Waboxapp
{
public string Token { get; set; }
public Contact Contact { get; set; }
}
public class Contact
{
public string Name { get; set; }
public string Type { get; set; }
}
Action
[HttpPost]
public IActionResult WaboxappFromForm([FromForm]Waboxapp waboxapp)
{
return View();
}
Request
Result

webapi not recognize json list

I've got a list of objects in JSON that isn't recognized by a WebApi2 controller
The JSON list is the following:
{
"FirstObjectType": [{"Name": "the_name"}],
"SecondObjectType": [{"Label": "01_obj"}, {"Label": "02_obj"}]
}
The Model class is:
public class CompositeObject
{
[JsonProperty("FirstObjectType")]
public List<FirstObject> fo { get; set; }
[JsonProperty("SecondObjectType")]
public List<SecondObject> so { get; set; }
}
The controller is:
public IHttpActionResult PostList([FromBody] CompositeObject jsonList)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
List<FirstObject> fo_list = jsonList.fo;
foreach (var item in fo_list)
{
db.FirstObject.Add(item);
db.SaveChanges();
}
return StatusCode(HttpStatusCode.OK);
}
When I submit the Post action, the controller recognize both lists in CompositeObject jsonList as Null
There is a problem in your model, where names are not being matched. You have to update model as:
public class FirstObjectType
{
public string Name { get; set; }
}
public class SecondObjectType
{
public string Label { get; set; }
}
public class RootObject
{
public List<FirstObjectType> FirstObjectType { get; set; }
public List<SecondObjectType> SecondObjectType { get; set; }
}
I have assumed that FirstObjectType contains string with name Name and SecondObjectType contains string with name Label. Make sure to use same names for properties of FirstObjectType and SecondObjectType class as in JSON string.
The issue was in the client code because I missed to set the Content-type as application/json in the header section.
In this way the WebApi server doesn't recognize in the right way the JSON object (I think that the server look for a x-www-form-urlencoded type)
So, the code above is right, but I have found another solution
In the WebApi controller:
using Newtonsoft.Json.Linq;
public IHttpActionResult PostList([FromBody] JObject ReceivedObjectsList)
{
var receivedLists = ReceivedObjectsList.Properties();
List<FirstObject> fo = ReceivedObjectsList["FirstObjectType"].ToObject<List<FirstObject>>();
List<SecondObject> so = ReceivedObjectsList["SecondObjectType"].ToObject<List<SecondObject>>();
...
}

Categories

Resources