I have an app with API controller
and Manager to send Endpoint to controller
public static class DrEndpoints
{
public static string ExportFiltered(string searchString)
{
return $"{Export}?searchString={searchString}";
}
public static string Export = "api/v1/Dr/export";
public static string LabAgenda = "api/v1/Dr/laborders";
public static string GetAll = "api/v1/Dr";
public static string Delete = "api/v1/Dr";
public static string Save = "api/v1/Dr";
public static string GetCount = "api/v1/Dr/count";
}
public async Task<IResult<List<GetAllDailyAgendasResponse>>> GetLabAgendaAsync(DateTime? date)
{
string str = $"{Routes.DrEndpoints.LabAgenda}/{date}";
var response = await _httpClient.GetAsync($"{Routes.DrEndpoints.LabAgenda}/{date}");
return await response.ToResult<List<GetAllDailyAgendasResponse>>();
}
[HttpGet("laborders/{date:datetime}")]
//[HttpGet("laborders/{date:datetime:regex(
//[HttpGet("laborders/{*date:datetime:regex(
//[HttpGet("laborders/{date:datetime}")]
public async Task<IActionResult> GetLabAgenda( DateTime date)
{
var brands = await _mediator.Send(new GetAllDailyAgendaQuery() { Atdate= date });
return Ok(brands);
}
IT Work fin in Swagger but when send data from any other front end return error like below
crit: Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
Unhandled exception rendering component: '<' is an invalid start of a value. Path: $ | LineNumber: 0 | BytePositionInLine: 0.
My Error case of date parameter please any help
Related
In my API I have a Create method in my controller that accepts all of the models fields, but in the method I'm excluding the ID field since on a create it's generated. But in Swagger it's showing the following.
Is there a way for it not to show the following part?
"id": 0
Is a viewmodel how I should go about this?
I tried the following, but can't get it to work.
public class PartVM
{
public string Name { get; set; }
}
public interface IPartService
{
Task<Part> CreatePart(PartVM part);
Task<IEnumerable<Part>> GetParts();
Task<Part> GetPart(int partId);
}
public class PartService : IPartService
{
private readonly AppDbContext _appDbContext;
public PartService(AppDbContext appDbContext)
{
_appDbContext = appDbContext;
}
public async Task<Part> CreatePart(PartVM part)
{
var _part = new Part()
{
Name = part.Name
};
var result = await _appDbContext.Parts.AddAsync(_part);
await _appDbContext.SaveChangesAsync();
return result.Entity;
}
}
Here's my controller.
[Route("api/[controller]")]
[ApiController]
public class PartsController : ControllerBase
{
private readonly IPartService _partService;
public PartsController(IPartService partService)
{
_partService = partService;
}
[HttpPost]
public async Task<ActionResult<Part>> CreatePart(PartVM part)
{
try
{
if (part == null)
return BadRequest();
var _part = new Part()
{
Name = part.Name
};
var createdPart = await _partService.CreatePart(_part);
return CreatedAtAction(nameof(GetPart),
new { id = createdPart.Id}, createdPart);
}
catch (Exception /*ex*/)
{
return StatusCode(StatusCodes.Status500InternalServerError, "Error creating new record in the database");
}
}
I'm getting a build error saying "CS1503 Argument 1: cannot convert from 'MusicManager.Shared.Part' to 'MusicManager.Server.Data.ViewModels.PartVM'".
It's refering to "_part" in this line "var createdPart = await _partService.CreatePart(_part);".
Any help is appreciated, thank you!
you have a CreatePart method which receives a PartVM model, but you are sending a Part Model to it
change your method to this :
public async Task<Part> CreatePart(Part part)
{
var result = await _appDbContext.Parts.AddAsync(_part);
await _appDbContext.SaveChangesAsync();
return result.Entity;
}
In below code, I need to read value of variable from request and modify request object.
public class ApiAuthFilter : AuthorizeAttribute, IAuthorizationFilter
{
public void OnAuthorization(AuthorizationFilterContext context)
{
// 1. read request object from context
// 2. modify the value
// 3. add the value and update request
}
}
You could modify request object like below:
1.User:
public class User
{
public int Id { get; set; }
public string Name { get; set; }
}
2.ApiAuthFilter:
public class ApiAuthFilter : Attribute, IAuthorizationFilter
{
public void OnAuthorization(AuthorizationFilterContext context)
{
//1.read request object from context
var request = context.HttpContext.Request;
request.EnableRewind();
request.Body.Position = 0;
using (var reader = new StreamReader(request.Body))
{
//2.modify the value
var decriptedFromJavascript = "{ \"Id\":2,\"Name\":\"UR123456\"}";
byte[] bytes = Encoding.ASCII.GetBytes(decriptedFromJavascript);
//3. add the value and update request
request.Body = new MemoryStream(bytes);
}
}
}
3.Action:
[HttpPost("[action]")]
[ApiAuthFilter]
public User GetUser([FromBody]User user)
{
return user;
}
4.Result:
public void OnAuthorization(AuthorizationFilterContext context)
{
string authHeader = context.HttpContext.Request.Headers["Authorization"];
context.HttpContext.Request.Headers["Authorization"] = "value";
}
I have to send a request object via Refit which contains 2 IEnumerable and one string, but for some reason I can't send the object forward.
I've tried to use all the paramets from the interface. Ex: [Query(CollectionFormat.Csv)] or Multi / Pipes but no success.
I've also tried to create my own CustomUrlParameterFormatter but unfortunately here I'm stuck, because I don't see a good way to retrieve the name of the property from the object request that I'm sending.
The code for CustomUrlParameterFormatter
public class CustomUrlParameterFormatter : IUrlParameterFormatter
{
public string Format(object value, ParameterInfo parameterInfo)
{
if(value is IEnumerable enumerable)
{
var result = ToQueryString(enumerable, parameterInfo.Name);
return result;
}
return string.Empty;
}
public static string ToQueryString(IEnumerable query, string parameterName)
{
var values = query.Cast<object>().Select(ToString).ToArray();
var separator = parameterName + "=";
return values.Any() ? separator + string.Join("&" + separator, values) : "";
}
public static string ToString(object value)
{
var json = JsonConvert.SerializeObject(value).Replace("\\\"", "\"").Trim('"');
return Uri.EscapeUriString(json);
}
}
The Call from the IService that I'm using
[Get("/TestMethod")]
Task<HttpResponseMessage> TestMethod([Query]TestRequestDTO requestDTO, [Header("X-Correlation-ID")] string correlationId);
The Request object
public class TestRequestDTO
{
public IEnumerable<long> EnumOne { get; set; }
public IEnumerable<long> EnumTwo { get; set; }
public string MethodString { get; set; }
}
Also the RefitClient configuration
var refitSettings = new RefitSettings();
refitSettings.UrlParameterFormatter = new CustomUrlParameterFormatter();
services.AddRefitClient<IService>(refitSettings)
.ConfigureHttpClient(c => c.BaseAddress = new Uri(settings.Services.IService));
What I'm trying to achieve is something like
TestMethod?EnumOne =123&EnumOne =321&EnumTwo=123&EnumTwo=321&methodString=asdsaa
and instead I'm receiving other behavior
without CustomUrlParameterFormatter()
TestMethod?EnumOne=System.Collections.Generic.List`1%5BSystem.Int64%5D&EnumTwo=System.Collections.Generic.List`1%5BSystem.Int64%5D&MethodString=sdf
i want to call other class method but its show me error. my other class is static class and static method please help me this how to solve this error. when compiler UHRCryptoManager its show above error
{"The type initializer for 'UHRServices.Manager.UHRCryptoManager'
threw an exception."}
Service1.svc
public class Service1 : System.Web.Services.WebService , IService1
{
public UHRResponse RequestApiToken(string CallerId)
{
UHRResponse response = new UHRResponse();
if (!String.IsNullOrEmpty(CallerId))
{
if (CallerId.Length >= 15 && CallerId.Length <= 32)
{
string UserAgent = Context.Request.Browser.Platform;
string ip = GetUserIP();
string ApiToken = UHRCryptoManager.GenerateApiToken("sadassdasdasdsadsd", "WinNT", "::1", 636549893023357954);
return response;
}
}
}
}
other class
public static class UHRCryptoManager
{
public static string GenerateApiToken(string callerid, string userAgent,string callerip, long ticks)
{
string hash = string.Join(":", new string[] { callerid, userAgent, ticks.ToString() , callerip });
}
}
I want to take a few post query parameters from an API i have and create a new entry. I wanted to do this with in the method with out needing to load context or something.
namespace fais.printing_services.Controllers
{
[Produces("application/json")]
[Route("api/[controller]/[action]")]
public class printController : Controller
{
private readonly IHostingEnvironment _appEnvironment;
public printController(IHostingEnvironment appEnvironment)
{
_appEnvironment = appEnvironment;
}
/**/
[HttpPost]
public IActionResult request(string id="test_default", string url = "", string html = "")
{
print_job _print_job = new print_job();
_print_job.html = html;
_print_job.options = options; //json object string
_print_job.url = url;
using (ApplicationDbContext db = new ApplicationDbContext())
{
db.print_job.Add(_print_job);
db.SaveChanges();
}
return Json(new
{
save = true
});
}
}
}
I just want to be able create a new print_job entry and save it when the API is called and return a json response.
Add ApplicationDbContext to controller constructor, it will be injected automatically (if your Startup.cs is like recommeneded):
private readonly IHostingEnvironment _appEnvironment;
private readonly ApplicationDbContext _db;
public printController(IHostingEnvironment appEnvironment, ApplicationDbContext db)
{
_appEnvironment = appEnvironment;
_db = db;
}
[HttpPost]
public IActionResult request(string id="test_default", string url = "", string html = "")
{
var _print_job = new print_job()
{
html = html,
options = options,
url = url,
}
_db.print_job.Add(_print_job);
_db.SaveChanges();
return Json(new { save = true });
}