I want to pass the data on the browser in Json format using .net core API:
[HttpGet("{id}")]
public ActionResult<IEnumerable< tenMinutes>> Get(string id)
{
var result= _context.tenmins.Where(s => s.m_turbine_id == IPAddress.Parse(id) && s.m_time_stamp >= DateTime.Now.AddDays(-1)).Take(2).ToList();
return result;
}
the id is the ip address when i rutn the project and put the breacpont on result,i have results in List,but when it returns nothing on browser i get Can’t reach this page,what is the reason?
Related
I have RESTful API that returns some large JSON files. I want to save the content to a file before sending it to the client. Here's my endpoint now:
[HttpPost]
[Route("rest/result")]
public IActionResult GetResult(string requestId)
{
var item = _service.GetItem(requestId);
return item?.Result == null ? NotFound() : Ok(item.Result);
}
I tried this code:
[HttpPost]
[Route("rest/result")]
public async Task<IActionResult> GetResult(string requestId)
{
var item = _service.GetItem(requestId);
var str = JsonSerializer.Serialize(item.Result);
await File.WriteAllTextAsync($"c:\\output\\{requestId}.json", str);
return item?.Result == null ? NotFound() : Ok(item.Result);
}
But the file is a bit different. Probably in terms of encoding because I'm seeing things such as : "Data":"{\u0027FnId\u0027:\u002710000149\u0027 in the file.
That shouldn't be any problem, as both representations are equivalent.
\u0027 is Unicode for apostrophe ('). So, special characters are returned in Unicode but will show up properly when rendered on the page:
"Data":"{'FnId':'10000149'}"
The Web API project is created in ASP.NET Core 2.2.
I have a POST method which accepts a custom class as parameter:
public async Task<IActionResult> MyWebMethod(Id id,
[FromBody] IReadOnlyCollection<MyCustomClass> instances)
{
// Process the data
return CreatedAtRoute("GetMyCollection",
new
{
id,
myIds = "someString";
},
responsesObject);
}
The code works fine when it receives a proper instance.
If the method receives any null parameter or an empty object from the client request, then I need to send back a 422 response to the client (422 Unprocessable Entity).
I placed some code within the method to handle such scenarios:
if (instances == null || instances.Count == 0)
{
return StatusCode(Convert.ToInt32(HttpStatusCode.UnprocessableEntity), instances);
}
But the issue is: whenever a null or an empty object is passed to the Web API method, the method does not get hit (when I try to debug the method).
What would be the best way to handle such request and send back a 422 response back to client?
Declare instances as default parameter and then check for null
public async Task<IActionResult> MyWebMethod(Id id,
[FromBody] IReadOnlyCollection<MyCustomClass> instances = null)
{
if (instances == null || instances.Count == 0)
{
return StatusCode(Convert.ToInt32(HttpStatusCode.UnprocessableEntity), instances);
}
//Proccess the data
}
So i have this ASP.NET Core on my local machine, i have installed the prerequisites and after running the application locally, the response was correct from the web browset that it was not found.
Okay, i am trying to invoked this API via Postman and i couldnt determine why i cant access it though i already checked the routings.
Below is the sample template
[HttpGet]
[Route("Details")]
public async Task<IActionResult> GetDetails(string value = null)
{
var response = new ListModelResponse<SomeModel>() as IListModelResponse<SomeModel>;
try
{
response.Model = await GetDetailsRepository
.GetDetailsSS(value)
.Select(item => item.ToViewModel())
.OrderBy(item => item.Name)
.ToListAsync();
}
catch (Exception ex)
{
response.DidError = true;
response.ErrorMessage = ex.Message;
}
return response.ToHttpResponse();
}
And in application insights of visual studio, i can see that it is invoking the API but it seems it can't get through.
Check this insights snippet
Other API's are working fine, it seems that i am missed something that i can't figure out right now.
For the routing i have this.
[Route("api/[controller]")]
I have also checked the Token and as i parsed it, i am getting the required info to access this API.
Thanks Lads!
It doesn't seem that you have the name of the controller in the request url.
api/[controller]/Details?value=CAT...
This error is due to the incorrect url present in the request. The correct URL has to be https://localhost:44309/api/your-controller-name/Details?value=CAT
ie. If the Controller name is ProductsController, then the URL has to be https://localhost:44309/api/Products/Details?value=CAT.
[Route("api/[controller]")]
public class ProductsController : Controller
{
[HttpPost("Details")]
public async Task<IActionResult> GetDetails(string value = null)
{
...
}
}
I have the following action that gets a Question model from my API given the Question title from an autocomplete input. The action is working fine with titles that do not contain a question mark (Ex. How old are you). But if I give a title containing a question mark (Ex. How old are you?) the model is not returned as the question mark is being removed in the process.
I tried HttpUtility.UrlDecode() method but with no luck .
Below you can find my requests
[HttpGet]
public async Task<IActionResult> GetQuestionAsync(string question) {
Questions q = new Questions();
HttpClient client = _api.Initial();
HttpResponseMessage res = await client.GetAsync("api/Search/" + question);
if (res.IsSuccessStatusCode) {
var result = res.Content.ReadAsStringAsync().Result;
q = JsonConvert.DeserializeObject<Questions>(result);
}
return View(q);
}
[Produces("application/json")]
[HttpGet]
[Route("{keyword}")]
public async Task<IActionResult> GetByString([FromRoute(Name = "keyword")] string keyword) {
if (!ModelState.IsValid) {
return BadRequest(ModelState);
}
var question = await _context.Questions
.SingleOrDefaultAsync(m => m.Question == HttpUtility
.UrlDecode(keyword.ToString()));
if (question == null) {
return NotFound();
}
return Ok(question);
}
I expect to be able to get questions including ? from my API. Is there a way to achieve this?
Note that in Swagger, the API Get request is working fine!
You need to use HttpUtility.UrlEncode - not Decode. You want to change the ? into an encoded character before sending it in the URL. HttpUtility.UrlDecode does the opposite.
i'm getting problems with deserialization.
I heaven don't know if include entities is possible in server side. I have this includes in Client side but for that i was not using the get service.
WebAPI Controller
// GET: api/UnidadeCurricular
[HttpGet]
public IEnumerable<UnidadeCurricular> GetUnidadeCurricular()
{
return _context.UnidadeCurricular.Include(c => c.Departamento)
.Include(c => c.Curso)
.Include(c => c.NomeUC)
.ToList();
}
WebApp Controller
// GET: Unidade_curriculares
public async Task<IActionResult> Index()
{
List<UnidadeCurricular> unidade_curricular = new List<UnidadeCurricular>();
string path = "api/UnidadeCurricular";
HttpResponseMessage response = await HttpRequestBuilder.WebApiClient.GetAsync(path);
//Checking the response is successful or not which is sent using HttpClient
if (response.IsSuccessStatusCode)
{
unidade_curricular = await response.Content.ReadAsAsync<List<UnidadeCurricular>>();
}
return View(unidade_curricular);
}
Erro https://i.stack.imgur.com/bygnF.png
Hi want to get the information about the FK's that i have in this table and for that i just include the other in the context but when the service is call the error shows and i can't understand why it stops the desirialization.