How to retrieve JsonResult data - c#

I have the following Action in my layouts Controller
public JsonResult getlayouts(int lid)
{
List<layouts> L = new List<layouts>();
L = db.LAYOUTS.Where(d => d.seating_plane_id == lid).ToList()
return new JsonResult { Data = L, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
I am calling this Action from another controller like so:
layoutsController L = new layoutsController();
JsonResult result = L.getlayouts(lid);
My question is: how can I get the data from result object?

Well, have a look how you're building the object:
new JsonResult { Data = L, JsonRequestBehavior = JsonRequestBehavior.AllowGet }
You're setting the L variable to a property called Data. So just read that property:
List<layouts> L = (List<layouts>)result.Data;
There's nothing special about the fact that it's an MVC controller action.
You're simply calling a method which returns an object that was constructed in the method, and reading properties from that object. Just like any other C# code.

I have my class:
public class ResponseJson
{
public string message { get; set; }
public bool success { get; set; }
}
in my method SendEmail
private async Task<JsonResult> SendEmailAsync(ApplicationUser user, string returnUrl, string empleadoNombre, string pwdInic)
i will return my JsonResult
ResponseJson response = new ResponseJson();
response.success = true;
response.message = "OperaciĆ³n exitosa";
return new JsonResult( response);
to read the result returned from my SendEmail method
JsonResult emailSend = await SendEmailAsync(user, returnUrl, empleadoNombre, pwdInic);
ResponseJson response = new ResponseJson();
try
{
string json = JsonConvert.SerializeObject(emailSend.Value);
response = JsonConvert.DeserializeObject<ResponseJson>(json);
}
catch(Exception e)
{
}

Related

Json API isnt returning data

I am trying to create a simple web API.
I have data going into the controller but I can't return it in the JSON API. I think the problem is returning the IEnumerable String.
BLL:
public IEnumerable<DTO.Gettod> Gettods()
{
DAL.todDataController tdc = new DAL.todDataController();
return tdc.GetToddMobiles();
}
Model:
public class TodViewModel
{
public IEnumerable<DTO.Gettod> ModelGetTod { get; set; }
}
Controller:
public IEnumerable<string> Get()
{
BLL.todManager tm = new BLL.todManager();
Models.TodViewModel tvm = new Models.TodViewModel();
tvm.ModelGetTod = tm.Gettods().ToArray();
return tvm as IEnumerable<string>;
}
JSON file returns only a Null but I'm expecting an Array.
The Correct Code is below, crediting: Bruno in the below answer:
public IHttpActionResult GetToddData()
{
BLL.todManager tm = new BLL.todManager();
Models.TodViewModel tvm = new Models.TodViewModel();
tvm.ModelGetTod = tm.Gettods().ToList();
//HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, tvm.ModelGetTod as IEnumerable<string>);
return Ok(tvm.ModelGetTod);
}
Try changing your controller to the below:
Edit: Changing the accepted answer to what worked for the user
public IHttpActionResult GetToddData () {
BLL.todManager tm = new BLL.todManager ();
Models.TodViewModel tvm = new Models.TodViewModel ();
tvm.ModelGetTod = tm.Gettods ().ToList ();
//HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, tvm.ModelGetTod as IEnumerable<string>);
return Ok (tvm.ModelGetTod);
}
Also, debug and see if you are getting the expected values in the tvm.ModelGetTod property.

Checking For Json response is true or false in unit testing with Nunit?

This is my method..
public ActionResult AddModelAliasData(ModalAliasModel modalAliasModel)
{
if (!ModelState.IsValid)
{
ModelState.LogModelStateError();
throw new BusinessException("COMMON_ERROR");
}
var response = _vehicleDataBusinessService.AddModelAliasData(modalAliasModel);
return Json(response);
}
As i am new to unit testing ... I am confused for some things, for the given above method in controller we are getting the json response in return. I want to check whether the return Json we are getting back has success true or false How should i do it???
The Response object result is
public class GetVehicleDataAliases : DefaultResponse
{
public List<SearchData> FindData { get; set; }
public List<VehicleDto> MakeDtos { get; set; }
}
The defaultResponse are Success , ErrorCode, ErrorMessage
I had wrote the unit test for this
[Test]
public void ShouldReturnJsonInAddMakeAlias()
{
var data = new GetVehicleDataAliases
{
MakeDtos = new List<VehicleDto>(),
Success = true,
FindData = new List<SearchData>()
};
mockVehicleDataBusinessService.Setup(x => x.AddMakeAliasData(It.IsAny<MakeAliasModel>())).Returns(() => data);
var vehicleDataController = new VehicleDataController(mockVehicleDataBusinessService.Object);
var result = vehicleDataController.AddMakeAliasData(makeAliasModel) as JsonResult;
Assert.AreEqual(data, result.Data);
}
But I am Able to clarify that is it the Right way to check for True or False Json result

Returning file data in JSON format

I have a txt file which has some data in it. I would like to return the data in JSON format.
Why is it that when i do this in my controller, i am able to display the result (but not in JSON format):
public IHttpActionResult Get()
{
return new FileReaderClient("C:\\Users\\attsuap1\\Desktop\\1milliontest.txt");
}
However when i do this i get the result as: {"Data":{}}
public IHttpActionResult Get()
{
var result = new FileReaderClient("C:\\Users\\attsuap1\\Desktop\\1milliontest.txt");
return Ok(new { Data = result });
}
If i just return result:
public IHttpActionResult Get()
{
var result = (new FileReaderClient("C:\\Users\\attsuap1\\Desktop\\1milliontest.txt"));
return result;
}
I do get the data however it is not in the Json format that i want e.g. {"Data": "Allthecontentinhere"}. I tried return Json(result) that did not work too.
Here is my FileReaderClient.cs class
public class FileReaderClient : IHttpActionResult
{
private readonly string filePath;
private readonly string contentType;
public FileReaderClient(string filePath, string contentType = null)
{
this.filePath = filePath;
this.contentType = contentType;
}
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
return Task.Run(() =>
{
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StreamContent(File.OpenRead(filePath))
};
var contentType = this.contentType ?? MimeMapping.GetMimeMapping(Path.GetExtension(filePath));
response.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
return response;
}, cancellationToken);
}
}
How can i edit my code such that the data in the file is returned in JSON format?
You can use 'JsonConvert' / NewtonSoft's JSON.Net Library,
var million_records;
using(StreamReader sr = new StreamReader(Server.MapPath("~/Uploads/1milliontest.json")))
{
million_records= JsonConvert.DeserializeObject<List<MillionData>>(sr.ReadToEnd());
}
return million_records;
Hope this helps.
--- N Baua

Support for Protobuf-net with requests in Web Api

I have a web api that I created and is able to take a JSON object post so long as the object Content-Type is application/json. We want to use protobuf from mobile devices to send data to the web api. If I switch the Content-type to x-protobuf and despite having this formatter added to my WebApiConfig
config.Formatters.Add(new ProtoBufFormatter());
When I use the Chrome extension "Advanced Rest Client" or Fiddler, it looks like the Web Api will send out a serialized response when I do a Get, but I do not see it receiving the post request when set to protobuf.
The test method header from the Controller class looks like this so far:
[HttpPost]
public override async Task<LoginResponse> Post([FromBody]LoginRequest request)
{...}
What more do I need to ensure that my WebApi will de-serialize the protobuf-serialized request.
What do you need to see to help? Please and thank you for your consideration.
The client has to send the request with protobuf serialization. Advanced Rest Client (or Fiddler) does not serialize the object. I wrote a test harness client that serialized the object like
byte[] rawBytes = ProtoBufSerializer.ProtoSerialize<LoginRequest>(loginRequest);
var client = new HttpClient();
client.BaseAddress = new Uri("http://localhost/");
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/x-protobuf"));
var byteArrayContent = new ByteArrayContent(rawBytes);
byteArrayContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-protobuf");
var result = client.PostAsync("Api/Login", byteArrayContent).Result;
Here is an example with proto definition, back-end and front-end code with RestClient.Net.
Proto definition
message Person {
string PersonKey = 1;
string FirstName = 2;
string Surname=3;
Address BillingAddress = 4;
}
message Address {
string AddressKey = 1;
string StreeNumber = 2;
string Street=3;
string Suburb=4;
}
Code Reference
Controller:
[ApiController]
[Route("[controller]")]
public class PersonController : ControllerBase
{
[HttpGet]
public IActionResult Get()
{
var person = new Person
{
FirstName = "Sam",
BillingAddress = new Address
{
StreeNumber = "100",
Street = "Somewhere",
Suburb = "Sometown"
},
Surname = "Smith"
};
var data = person.ToByteArray();
return File(data, "application/octet-stream");
}
[HttpPost]
public async Task<IActionResult> Post()
{
var stream = Request.BodyReader.AsStream();
return File(stream, "application/octet-stream");
}
[HttpPut]
public async Task<IActionResult> Put()
{
var stream = Request.BodyReader.AsStream();
var person = Person.Parser.ParseFrom(stream);
if (!Request.Headers.ContainsKey("PersonKey")) throw new Exception("No key");
person.PersonKey = Request.Headers["PersonKey"];
var data = person.ToByteArray();
return File(data, "application/octet-stream");
}
}
Code Reference
Serialization:
public class ProtobufSerializationAdapter : ISerializationAdapter
{
public byte[] Serialize<TRequestBody>(TRequestBody value, IHeadersCollection requestHeaders)
{
var message = (IMessage)value as IMessage;
if (message == null) throw new Exception("The object is not a Google Protobuf Message");
return message.ToByteArray();
}
public TResponseBody Deserialize<TResponseBody>(byte[] data, IHeadersCollection responseHeaders)
{
var messageType = typeof(TResponseBody);
var parserProperty = messageType.GetProperty("Parser");
var parser = parserProperty.GetValue(parserProperty);
var parseFromMethod = parserProperty.PropertyType.GetMethod("ParseFrom", new Type[] { typeof(byte[]) });
var parsedObject = parseFromMethod.Invoke(parser,new object[] { data });
return (TResponseBody)parsedObject;
}
}
Code Reference
Usage:
var person = new Person { FirstName = "Bob", Surname = "Smith" };
var client = new Client(new ProtobufSerializationAdapter(), new Uri("http://localhost:42908/person"));
person = await client.PostAsync<Person, Person>(person);
Code Reference

What does HttpResponseMessage return as Json

I have a basic question about basics on Web Api. FYI, I have checked before but could not found what I was looking for.
I have a piece of code as described below these lines. Just like any other Method in general terms my method called: Post, it has to return something,a JSON for example, How do I do that.
Specifically, what am I supposed to write after the word " return " in order to get the 3 fields( loginRequest.Username,loginRequest.Password,loginRequest.ContractItemId ) as Json.
Coments: Do not worry about username,password and contractID are in comments, I do get their value in my LinQ. It's just the return whta I nened now, greetings to all who would like to throw some notes about this.
[System.Web.Http.HttpPost]
public HttpResponseMessage Post(LoginModel loginRequest)
{
//loginRequest.Username = "staw_60";
//loginRequest.Password = "john31";
//loginRequest.ContractItemId = 2443;
try
{
Membership member =
(from m in db.Memberships
where
m.LoginID == loginRequest.Username
&& m.Password == loginRequest.Password
&& m.ContractItemID == loginRequest.ContractItemId
select m).SingleOrDefault();
}
catch (Exception e)
{
throw new Exception(e.Message);
}
return ???;
}
Try this:
HttpResponseMessage response = new HttpResponseMessage();
response.Content = new ObjectContent<Response>(
new Response() {
responseCode = Response.ResponseCodes.ItemNotFound
},
new JsonMediaTypeFormatter(), "application/json");
or just create another response from Request object itself.
return Request.CreateResponse<Response>(HttpStatusCode.OK,
new Response() { responseCode = Response.ResponseCodes.ItemNotFound })
You can also turn all your response types to JSON by updating the HttpConfiguration(Formatter.Remove) just remove the default xml serialization and put JSON.
You could perhaps create a LoginResponseModel class that you can use to send back information to the caller about the success/failure of the login attempt. Something like:
public class LoginResponseModel
{
public bool LoginSuccessful {get; set;}
public string ErrorMessage {get; set;}
public LoginResponseModel()
{
}
}
Then you can return this directly from the controller if you like:
[System.Web.Http.HttpPost]
public LoginResponseModel Post(LoginModel loginRequest)
{
...
return new LoginResponseModel() { LoginSuccessful = true, ErrorMessage = "" };
}
Or you can still use a HttpResponseMessage as return type, but send a LoginResponseModel as the json response:
[System.Web.Http.HttpPost]
public HttpResponseMessage Post(LoginModel loginRequest)
{
...
var resp = Request.CreateResponse<LoginResponseModel>(
HttpStatusCode.OK,
new LoginResponseModel() { LoginSuccessful = true, ErrorMessage = "" }
);
return resp;
}

Categories