I am trying to receive the curl request in my web API method. Below is the request that will be send by the user. I am trying to receive this request in web api but i am not able to do this.
Can you please suggest me how can i do this.
Array
(
[post_data] => Array
(
[DL] => 2
[ID] => 8NNGQ8Q5
[ShipCity] => CLEARWATER
[ShipState] => FL
[ShipZip] => 33762
[ShipCountry] => US
)
Trying to create a web API method for the same.
public HttpResponseMessage GetQuote(HttpRequestMessage request, [FromBody] Request model)
{
try
{
var abf = Request.Content.ReadAsStringAsync();
return request.CreateResponse(HttpStatusCode.OK, abf);
}
catch (Exception)
{
return request.CreateResponse(HttpStatusCode.BadRequest);
}
}
Related
I'm developing an application in Angular and .Net, it consists of creating projects -like Asana- each project has a creator, so there I made the connection, I related the table of users and projects to create the foreign key (userCreationId).
It's a POST request, this is my service:
public string ObtenerUsuarioId()
{
if (httpContext.User.Identity.IsAuthenticated)
{
var idClaim = httpContext.User.Claims
.Where(x => x.Type == ClaimTypes.NameIdentifier).Single();
return idClaim.Value;
}
else
{
throw new Exception("El usuario no está autenticado");
}
}
And the controller:
public async Task<IActionResult> Post([FromBody] ProyectoCreacionDTO proyectoCreacionDTO)
{
var proyecto = mapper.Map<Proyecto>(proyectoCreacionDTO);
var usuarioId = servicioUsuarios.ObtenerUsuarioId();
proyecto.UsuarioCreacionId = usuarioId;
context.Add(proyecto);
await context.SaveChangesAsync();
return Ok(proyecto);
}
But the request in Angular does not bring me the claims, and it falls in the else of my service in .net.
It doesn't read the email and the id.
error : "System.Exception: User isn't authenticated \r\n.
Which is the else of my service.
I tried the request on POSTMAN and it works:
It does read the email!
And I get the answer I was expecting:
A successful answer
But then again when I tried this in Angular it doesn't work, and I'm saving the token in LocalStorage
login(email:string, password:string):Observable<Login>{
return this.http.post<Login>(`${this.url}/login`, {email, password})
.pipe(
tap(resp => {
this.localStorage.getToken(resp.token)
})
)
crearProyecto(proyecto:Proyecto):Observable<Proyecto>{
return this.http.post<Proyecto>(`${this.url}/agregar`, proyecto)
The token is actually saved, I can protect routes with AuthGuards, so I dont know why when I send the request from Angular it doesn't work
Here is the token
I even have the Cookie that Identity generates:
The cookie
I have code to allow us to use the NetSuite REST API using OAuth 1.0. Everything works fine, except one call. When trying to do /salesorder/{id}/!transform/itemFulfillment It fails with 401. All other calls work fine. When I execute the same call from Postman it works fine too. What am I missing?
Here is my Code:
private static async Task CreateItemFulFillmentsAsync(NetSuiteJob job, int id, Item item)
{
RestRequest request = new RestRequest($"{job.RecordUrl}/salesorder/{id}/!transform/itemFulfillment", Method.Post);
request.AddBody(item);
RestHelper restHelper = new RestHelper();
RestResponse response = await restHelper.ExecuteRestRequest(request, job);
if (response == null || !response.IsSuccessful)
{
throw new Exception($"Failed to create the Item Fulfillment for the Sales Order: {id}.\r\n" + response.Content);
}
}
And the Helper Class:
public async Task<RestResponse> ExecuteRestRequest(RestRequest request, NetSuiteJob job)
{
RestClient client = new RestClient(job.BaseUrl) { Authenticator = GetOAuth1Authenticator(job) };
RestResponse response = await client.ExecuteAsync(request);
return response;
}
private OAuth1Authenticator GetOAuth1Authenticator(NetSuiteJob job)
{
OAuth1Authenticator oAuth1 = OAuth1Authenticator.ForAccessToken(
consumerKey: job.ConsumerKey,
consumerSecret: job.ConsumerSecret,
token: job.TokenId,
tokenSecret: job.TokenSecret,
OAuthSignatureMethod.HmacSha256);
oAuth1.Realm = job.Realm;
return oAuth1;
}
The results are:
{"type":"https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.2",
"title":"Unauthorized","status":401,
"o:errorDetails":[{"detail":"Invalid login attempt. For more details,
see the Login Audit Trail in the NetSuite UI at Setup > Users/Roles
> User Management > View Login Audit Trail.","o:errorCode":"INVALID_LOGIN"}]}
In NetSuite's Login Audit Trail, this call is logged as a failure and Role is blank, but the other calls using different action shows the Role like it should. The working routines use the same helper class but are doing it with a different URL and Body. I've verified the content being passed matches what I did manually in Postman too.
I have a .Net 5 Web API and would like to create a GET endpoint (acting as a subscription) sending data every x seconds. I know that there are tools out there, e.g. SignalR, but I would like to know if it is possible to achieve the same result with a simple route. Maybe a stream could help ...
This is my example controller
[ApiController]
[Route("[controller]")]
public class MyController : ControllerBase
{
[HttpGet]
public OkResult SendDataEvery5Seconds()
{
return Ok(); // send back an initial response
// send data every 5 seconds
}
}
I don't know if this is possible with C# but I tried to create a working example using Node showing what I want to achieve:
const express = require('express')
const app = express()
app.get('/', (req, res) => {
res.writeHead(200, {
'content-type': 'application/x-ndjson'
});
setInterval(() => {
res.write(JSON.stringify(new Date()) + '\n');
}, 5000);
})
app.listen(3000);
running curl -i http://localhost:3000 should write down a date every 5 seconds.
You can accomplish it like this.
Server code:
[HttpGet]
public async Task Get(CancellationToken ct = default)
{
Response.StatusCode = 200;
Response.Headers["Content-Type"] = "application/x-ndjson";
// you can manage headers of the request only before this line
await Response.StartAsync(ct);
// cancellation token is important, or else your server will continue it's work after client has disconnected
while (!ct.IsCancellationRequested)
{
await Response.Body.WriteAsync(Encoding.UTF8.GetBytes("some data here\n"), ct);
await Response.Body.FlushAsync(ct);
// change '5000' with whatever delay you need
await Task.Delay(5000, ct);
}
}
Corresponding client code (c# example):
var client = new HttpClient();
var response = await client.GetStreamAsync("http://localhost:5000/");
using var responseReader = new StreamReader(response);
while (!responseReader.EndOfStream)
{
Console.WriteLine(await responseReader.ReadLineAsync());
}
I am trying to get a File that is being sent (from Postman) in the body of a POST request to my REST API that is self hosted using Owin. While debugging I can confirm that the correct endpoint it being reached but HttpContext.Current returns null always. Pretty much HttpContext.anything returns null. So I don't understand how I am supposed to receive a File via POST request and process it in my REST API while using Owin self hosting. I have tried Request.GetOwinContext() but that doesn't return anything useful.
How do I achieve this?
The Request property of a controller can help access the file.
public class FileController : ApiController
{
[HttpPost]
public async Task Post()
{
if (Request.Content.IsMimeMultipartContent())
{
var multipartContent = await Request.Content.ReadAsMultipartAsync();
// "thefile" is the form field name
HttpContent httpContent = multipartContent.Contents
.Where(c => c.Headers.ContentDisposition.Name == "\"thefile\"")
.Single();
// httpContent contains the file, for example:
var fileContents = await httpContent.ReadAsStringAsync();
}
}
}
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.