Returning result for .net Web Api from db call - asp.net-mvc

I'm new to the .net Web API and am trying to figure out how I return a Get result from a call to my database. I know everything works in my regular MVC page. But Not sure how to return the result from the Web API controller. I thought it was as simple as returning Json with the result. Here is my code:
// GET api/<controller>
public IEnumerable<string> Get()
{
using (var _db = new JobsDatabaseEntities())
{
var user = Env.CurrentUser;
var posts =
_db.JobPostings.Where(
j =>
j.City.Equals(user.City, StringComparison.OrdinalIgnoreCase) &&
j.Industry.ID == user.Industry.ID);
var result = new List<BusJobPost>();
foreach (var post in posts)
{
var p = new BusJobPost(post);
result.Add(p);
}
return Json(result);
}
}

Please visit this resource: Action Results in Web API 2. Your case is described in fourth section Some other type (which is applicable to first version of Web API as well).
In Web API you don't return JSON result explicitly. It is actually done by process called Content Negotiation. You can read about it here [Content Negotiation in ASP.NET Web API] in detail.
Highlighting briefly just some of this:
You can set Accept header for you request as: Accept: application/json (for example, if you use jquery ajax function: dataType: 'json')
Or even if you don't use Accept header at all, if you send request with JSON data, you should also get response back in JSON format
So you should just return result variable from your controller action and satisfy some of conditions to get response serialized into JSON.

Related

Read API Response Messages

I have Developed ASP.net Core Web API & Web APP Which are in the same solution but different projects.
in the API I have some validations/checking as you may call.
e.g: if user email already exists, the API returns 'Email alreday in use' like this
bool EmailExists = dbContext.Users.Any(u => u.Email == user.Email);
if (EmailExists)
{
return new JsonResult("Email Address already taken!, Try a differen Email");
}
and so on. in some cases I may need to check multiple columns one a time, (eg: UserName, Email, TellNum)
This is an example of calling the API in the MVC
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(_baseAPIUrl);
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage Res = await client.PostAsJsonAsync("Users", user);
if (Res.IsSuccessStatusCode)
{
//in here I want check the `Res` and if it contains the returned messages, I want to display them by assigning it to `TempData[infoMsg]`
// else some something(register user)
}
// Check the returned JsonResult messages here if statusCode is ultered eg: BadRequest
}
My Question is how can I display these types of response messages in razor view in the MVC(Web App). in PostMan its workin, returning the response messages in body.
I did a lot of research about this but couldn't come to conclusion. I also cantacted some Devs I know(not .NET) and they said use JavaScript to call your API, which means I have to change almost everything I have done so far.
I aslo tried ultereing the statuCode to something like BadRequest in the API(if Email exists) in which case it will be checked outside the if (Res.IsSuccessStatusCode) of the Httpclient.
any help or direction is highly appreciated.
You should return a http error and a body containing some data about it eg field and message to your mvc controller. That could be a 422 error or whatever you like really since it's effectively internal and just coming back to the mvc controller.
The controller can then add any such error to modelstate and you can use the razor model "client" validation mechanism to show the error associated with a field.
This is therefore using the same mechanism used for attribute validation in the controller where you'd do
if (!ModelState.IsValid)
This is air code but will hopefully give you the idea.
[HttpPost]
public ActionResult PostUpdate(User u)
{
// call service and await response
var response = await httpClient.PostAsJsonAsync(posturi, u);
var returnContent = await response.Content.ReadAsAsync<ReturnContent>();
if (response.Result != HttpStatusCode.OK)
{
ModelState.AddModelError(returnContent.FieldName,returnContent.Error);
return Page();
}
// etc
You will want a more sophisticated checking on errors of course and check you get the body you're expecting.
Maybe you just hard code the field and error message if there's only one possibility. Maybe work with an array of fields and errors if there could be numerous validation fails.

return Json will redirects to another view when Url specified

When you do return Json(...) you are specifically telling MVC not to use a view, and to serve serialized JSON data. Your browser opens a download dialog because it doesn't know what to do with this data.
i got the above information from below link
How to return Json object from MVC controller to view
when i give this below code in some action result
return Json(new { Url = "sep/employee"}
whether it will redirect to specified action ? how it redirects to the URl ?
for this case why i cant use return RedirectToAction("sep/employee").
how return Json code redirects to action which specified in the Url.
ex:
public ActionResult Index()
{
................................
return Json(new { Url = "sep/employee"}
}
public ActionResult employee()
{
....................
}
what is the difference b/s redirectaction and return Json
You return the following line to an ajax success call
return Json(new { Url = "sep/employee"});
you then need to specify where to redirect to the new page
success: function(result) {
window.location.href=result.Url;
}
RedirectToAction simply returns 302 code to your browser with URL telling where the browser should redirect to. The browser immediately makes yet another call to the server to that URL obtained from redirection response.
RedirectToAction internals are:
Construct redirection url from parameters passed to RedirectToAction
Return new RedirectToRouteResult
In ExecuteResult of RedirectToRouteResult you can find the following line:
context.HttpContext.Response.Redirect(destinationUrl, endResponse: false);
which is merely returning 302 with redirection URL. More info - look at source code here.
Returning JSON data simply returns JSON serialized object to your browser. Is not meant to do any redirect. To consume such a result you will likely call the server using $.ajax:
$.ajax({
url: 'sep/employee',
type: 'POST'
success: function(result) {
// handle the result from the server, i.e. process returned JSON data
}
});
ExecuteResult of JsonResult just serializes passed CLR object to the response stream, which lands in your browser after response is fully received. Then you can handle such response in JavaScript code.
EDIT:
You of course can mimic 302 redirection by returning Json like
return Json(new { Url = "redirectionUrl"}
and at client side handle it like
$.ajax({
url: 'sep/employee',
type: 'POST'
success: function(result) {
// mimic the 302 redirection
windows.location.href = result.Url
}
});
although IMHO it should be avoided since you reinvent MVC infrastructure and enlarge your code base.
whether it will redirect to specified action ? how it redirects to the URl ?
I assume you mean to ask, "will it redirect to specified action? how will it redirect the the URI?"
To answer your question: How it redirects to the URL?
In your example it will redirect to the URL, if you made the HTTP request as AJAX and that you will explicitly handle the resulting HTTP response to actually redirect to the URL that you received. So your view should have something like this:
$.ajax({
url: '{your controller}/index',
type: 'GET'
success: function(url) {
// write code to redirect to the URL
// example:
// window.navigate(url)
}
});
If your view does not have anything that, then it will not redirect. You did not post your view, so I am assuming it just a normal page load.
Your next question, what is the difference b/s redirection and return Json?
If you really just want to redirect then do RedirectToAction from your controller, that is exactly what it is for. You can do the same effect using AJAX and JSON to be able to redirect, but AJAX and JSON serves a much wider purpose than just redirecting and in most cases (unless you have very good reasons) you probably will not want replace RedirectToAction with that approach.

How to send data from client to server using Rikulo stream

I'm trying to use Rikulo stream, and i have some trouble when i want to send data from client to server.
Suppose that i have a registration form and i want send a request to check if that username already exist in my database.
I have adopted MVC pattern, so i want that the controller received data and then, using a dao class, check if username exist or not.
In client side i have this lines of code
InputElement username = query('#username');
document.query("#submit").onClick.listen((e) {
HttpRequest request = new HttpRequest();
var url = "/check-existing-username";
request.open("POST", url, async:true);
request.setRequestHeader("Content-Type", "application/json");
request.send(stringify({"user": username.value}));
});
Is this the correct way to send data?
Here my server side code
void main(){
Controller controller = new Controller();
var _mapping = {
"/": controller.home,
"/home": controller.home,
"/check-existing-username" : controller.checkUsername
};
new StreamServer(uriMapping: _mapping).start();
And my controller method
void checkUsername(HttpConnect connect) {
//How to access data received from client?
}
The dao class is already defined, so i want only know how to access data.
I hope that someone can help me.
Since you're using POST, the JSON data will be in the HTTP request's body. You can retrieve it there. Rikulo Commons has a utility called readAsJson. You can utilize it as follows.
import "package:rikulo_commons/convert.dart";
Future checkUsername(HttpConnect connect) {
return readAsJson(connect.request).then((Map<String, String> data) {
String username = data["user"];
//...doa...
});
}
Notice that reading request's body is asynchronous, so you have to return a Future instance to indicate when it is done.

Using JSON data in ASP.NET MVC

I have not done this before, so need some leads. I have a ASP.NET MVC4 (beta) project - Mobile project - setup. And I am given a set of REST APIs to consume. How would I do this? The APIs return data in JSON format. Do you have any examples, best practices...?
You could use the $.ajax method to send an AJAX request to the Web Api controller on the server:
$.ajax({
url: 'api/values/123',
type: 'GET',
success: function(data) {
// if the controller returned JSON data, the data argument
// will represent a javascript object that you could directly
// access its properties
}
});
Use DownloadString method of WebClient class. That will give you a string output of what the RESTURL is returning. You can convert that to Json and iterate the results
string address="http://yourrestdomain/customer/234";
WebClient client = new WebClient ();
string reply = client.DownloadString (address);

ASP.Net MVC 3 WebFormsViewEngine HTML Helpers and JSON data

I would like to know if is possible in ASP.Net MVC 3, using Web forms view engine and HTML Helpers, and the client side we are using Ext.Js to generate the grids.
The problem is when I return JSON(data) for the Ext.JS grid and the HTML Helper.
The HTML Helper is not able to render the JSON element.
It pops-up a window asking "What firefox should do with this file?".
I've tried to use:
return this.Json(new { objectJson = object}, "text/html", JsonRequestBehavior.AllowGet);
And it returned a new page with the HMTML Code, didn't bind to the HTML Helpers. I also tried without the JsonRequestBehavior.AllowGet and the result was:
This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet.
And even if I change the MIME type of the Header to application/json and make the method's return as JSONResult instead of ActionResult it still doesn't recognize the file.
return this.Json(new { IssueInventoryPartModel = issueInventoryPartmodel, success = true }, "application/json", JsonRequestBehavior.AllowGet);
Briefly the question is: The HTML Helper for Web Form View Engine binds with JSON?
Best regards,
Tito
I had this problem while sending html data via json, and solved it by adding contenttype to the jsonresult, in the server side action method (called via js in client side), there should be something like :
return Json(dataToReturn, "text/html")
it sounds like the content-type for the action result is not being set properly
how about including JsonRequestBehavior.AllowGet on the return of the JSON as in:
return Json(new
{
data = components,
success = true
}, JsonRequestBehavior.AllowGet);

Resources