Danke Dir, dachte das muss doch etwas neues sein...
Werde ich mir anschauen und gegebenenfalls umsetzen.
Gruss Lhyn
Hallo zusammen,
Habe es nun mit [Produces("application/json")] getestet und Accept ist nun im Json-Format, danke dafür.
CreatedAtAction knallt aber leider noch immer.
Bin kurz davor es mit einem return Ok(project.AsDto()); zu basteln 😉
@Abt, kannst Du bitte genauer auf Deine Lösung für mein Beispiel eingehen?
Habe mir vorhin die Doku angeschaut und nach Umsetzungen gegoogelt, leider ohne Erfolg
Scheint als arbeiten noch nicht viele mit dem LinkGenerator für Routing
Gruss Lhyn
Hallo T-Virus,
Danke Dir für die schnelle Antwort.
Routing:
[ApiController]
[Route("api/[controller]")] // api/Project
Muss mich mal schlau machen, wie ich produces = application/json einstellen kann.
Habe ich auf die schnelle nicht herausgefunden...
Gruss Lhyn
Hallo zusammen,
Ich habe ein Problem mit meiner WebAPI, welche ich "modernisieren" möchte und finde den Fehler nicht.
Beim Aufruf der folgenden Methode wird bei CreatedAtAction ein Fehler im Swagger ausgegeben.
// POST /api/Project
[HttpPost]
public async Task<ActionResult<ProjectDto>> CreateProjectAsync([FromBody] CreateProjectDto projectDto)
{
var existingId = await repository.GetProjectByIdAsync(projectDto.Id);
if(existingId is null)
{
ProjectModel project = new()
{
Uid = projectDto.Uid
};
// Projekt wird dem InMemProjectRepository korrekt hinzugefügt
await repository.CreateProjectAsync(project);
// Hier, bei der CreatedAtAction tritt der Fehler auf
return CreatedAtAction(nameof(GetProjectByIdAsync), new { id = project.Id }, project.AsDto());
}
else if(existingId.Id == projectDto.Id)
{
return BadRequest();
}
return BadRequest();
}
// GET /api/Project/{id}
[HttpGet("{id}")]
public async Task<ActionResult<ProjectDto>> GetProjectByIdAsync(int id)
{
var project = await repository.GetProjectByIdAsync(id);
if (project is null)
{
return NotFound();
}
return project.AsDto();
}
Fehlermeldung:
System.InvalidOperationException: No route matches the supplied values.
at Microsoft.AspNetCore.Mvc.CreatedAtActionResult.OnFormatting(ActionContext context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ObjectResultExecutor.ExecuteAsyncCore(ActionContext context, ObjectResult result, Type objectType, Object value)
at Microsoft.AspNetCore.Mvc.Infrastructure.ObjectResultExecutor.ExecuteAsync(ActionContext context, ObjectResult result)
at Microsoft.AspNetCore.Mvc.ObjectResult.ExecuteResultAsync(ActionContext context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeResultAsync(IActionResult result)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext[TFilter,TFilterAsync](State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeNextResultFilterAsyncTFilter,TFilterAsync
--- End of stack trace from previous location ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResultExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext[TFilter,TFilterAsync](State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeResultFilters()
--- End of stack trace from previous location ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)HEADERS
=======
Content-Type: application/json
:authority: localhost:5001
:method: POST
:path: /api/Project
😒cheme: https
Accept: text/plain
Accept-Encoding: gzip, deflate, br
Accept-Language: de-CH,de-DE;q=0.9,de;q=0.8,en-US;q=0.7,en;q=0.6
Cookie: ai_user=nITrk|2022-01-04T22:21:05.590Z,ai_session=TVQAp|1641372830052|1641372830052
Host: localhost:5001
Referer: https://localhost:5001/swagger/index.html
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36
Origin: https://localhost:5001
Content-Length: 72
sec-ch-ua: " Not A;Brand";v="99", "Chromium";v="96", "Google Chrome";v="96"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "Windows"
sec-fetch-site: same-origin
sec-fetch-mode: cors
sec-fetch-dest: empty
Ich danke Euch für die Unterstützung.
Gruss Lhyn
Hallo dannoe,
Ich danke Dir für die Antwort, hat mit Deiner Hilfe gut geklappt.
Unter Import konnte ich cURL auswählen und damit importieren.
Gruss Lhyn
Hallo zusammen,
Ich möchte mich mit einer Web API via Postman verbinden und dazu wird OAuth 2.0 verwendet.
-> ClientId und CleintSecret habe ich
In der Doku der Web API steht ich soll mich für die Schlüsselgenerierung wie folgt verbinden:
curl -X POST \
'https://api.asdf.de/oauth/accesstoken?grant_type=client_credentials' \
-H 'Authorization: Basic base64<ClientId:CleintSecret>' \
-H 'Cache-Control: no-cache' \
-H 'Content-Length: 0' \
-H 'Postman-Token: xxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
Dann erhalte ich unter anderem den Schlüssel als Antwort.
Nun, ich habe keine Ahnung wie ich das im Postman in ein Post bringe...
Gem. Google soll das etwas mit cURL sein 🙂
Ich danke Euch für die Unterstützung.
Gruss Lhyn
Hallo dannoe,
Du bist super, danke Dir nun funktioniert es 👍 😁
Gruss Lhyn
Hallo dannoe,
Nein, der sollte calculate heissen, da der Controller "CalculateController" heisst.
Ich habe schon so einiges probiert: https wie auch http
Dann nur über http://localhost:5000/calculate, da ich Task<IActionResult> Get() geschrieben habe.
Zum Schluss noch http://localhost:5000/calculate/getproject wie im Code gezeigt "[HttpGet("GetProject")]"
Gruss Lhyn
Hallo zusammen,
Ich versuche mich gerade an einer kleinen web-api und finde den Fehler nicht...
Alle Abfragen mit Postman geben kein JSON zurück 8o
Über den Debugger habe ich festgestellt, dass der HttpGet Request (via Postman) des CalculateController nie aufgerufen wird, mir gehen langsam die Ideen aus.
Startup.cs
namespace DPCalculator.Api
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddScoped<ICalculateService, CalculateService>();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
Models:
namespace DPCalculator.Api.Models
{
public class Project
{
public PlcType PlcType { get; set; } = PlcType.Test1;
public int NumberOfSelectedStations { get; set; }
}
}
namespace DPCalculator.Api.Models
{
public enum PlcType
{
Test1,
Test2,
Test3
}
}
Services:
namespace DPCalculator.Api.Services.CalculateService
{
public class CalculateService : ICalculateService
{
private Project _project = new Project();
public async Task<Project> GetProject()
{
return _project;
}
}
}
namespace DPCalculator.Api.Services.CalculateService
{
public interface ICalculateService
{
Task<Project> GetProject();
}
}
Controllers:
namespace DPCalculator.Api.Controllers
{
[ApiController]
[Route("controller")]
public class CalculateController : ControllerBase
{
private readonly ICalculateService _calculateService;
public CalculateController(ICalculateService calculateService)
{
_calculateService = calculateService;
}
[HttpGet("GetProject")]
public async Task<IActionResult> Get()
{
return Ok(await _calculateService.GetProject());
}
}
}
Hallo shazam,
Du arbeitest anscheinend mit Microsoft.Office.Interop.Excel was ein installiertes Excel benötigt.
Ist dieses auch wirklich installiert und lässt sich auf dem "Problem-PC" starten?
Als alternative kann ich Dir OpenXml empfehlen, damit kannst du viel performanter und ohne installiertes Excel eine xlsx Datei erzeugen.
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
Gruss Lhyn