|
OK, but do I have the method set up correctly?
In theory, theory and practice are the same. But in practice, they never are.”
If it's not broken, fix it until it is.
Everything makes sense in someone's mind.
|
|
|
|
|
The method looks OK, although you shouldn't really need the [FromBody] attribute.
For ASP.NET Core:
Route data and query string values are used only for simple types.
If you're still using WebAPI 2 in .NET Framework:
To force Web API to read a simple type from the request body, add the [FromBody] attribute to the parameter:
In either case, your parameter is not a "simple type", so it should be bound from the request body by default.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
OK, but even when I pass it in Postman from body, it still fails to find it. I'm not sure what's wrong
In theory, theory and practice are the same. But in practice, they never are.”
If it's not broken, fix it until it is.
Everything makes sense in someone's mind.
|
|
|
|
|
OK, so I'm still having some issues.
I created a new API and enabled Swagger. I added this controller method to the default out of the box WeatherForecastController:
[HttpPost("GetPersonInfo/{entity}")]
public IActionResult GetPersonInfo(PersonEntity person)
{
return StatusCode(200, $"{person.Id}: {person.Name}");
}
When I run it, and click the Try It Out button, I enter
{
"id": 135,
"name": "Jack Smith"
}
in the Body field and click Execute, and it works. I get back
135: Jack Smith
But when I go to Postman, and fill in the sample Json in the Body tab
{ "id": 135, "name": "Jack Smith"}
and call it
https:
I get a 404.
That's the URL right out of swagger and the body I used. Any idea what this doesn't work in Postman?
In theory, theory and practice are the same. But in practice, they never are.”
If it's not broken, fix it until it is.
Everything makes sense in someone's mind.
modified 21-Apr-24 18:39pm.
|
|
|
|
|
Kevin Marois wrote: [HttpPost("GetPersonInfo/{entity}")]
Assuming you're passing the JSON in the POST body, you shouldn't have the {entity} parameter as part of the route template.
Given the current route template, it looks like you're trying to pass the request body in the URL, which is the wrong thing to do.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
I'm trying to learn ASP.Net MVC Core API. I think I'm doing the routing wronge.
I have a UserController:
namespace Falcon.API.Controllers
{
[Route("api/user")]
[ApiController]
public class UserController : _ControllerBase
{
public UserController(IConfiguration configuration) :
base(configuration)
{
}
[HttpGet("getById/{id}")]
public IActionResult GetById(int id)
{
try
{
var repo = new Repository(GetDataContext());
var owner = repo.GetById(id);
if (owner is null)
{
return NotFound();
}
else
{
return Ok(owner);
}
}
catch (Exception ex)
{
return StatusCode(500, "Internal server error");
}
}
[HttpGet]
public IActionResult GetAll()
{
try
{
var repo = new Repository(GetDataContext());
var owners = repo.GetAll();
return Ok(owners);
}
catch (Exception ex)
{
return StatusCode(500, "Internal server error");
}
}
[HttpGet("login/{username}/{password}")]
public IActionResult Login(string userName, string password)
{
try
{
var repo = new UserRepository(GetDataContext());
var owner = repo.Login(userName, password);
if (owner is null)
{
return NotFound();
}
else
{
return Ok(owner);
}
}
catch (Exception ex)
{
return StatusCode(500, "Internal server error");
}
}
}
}
When I call it, I'm doing this:
public async Task Login(string userName, string password)
{
UserEntity results = null;
var url = $"https:// localhost:5001/api/User/Login/{userName}/{password}";
using (var httpClient = new HttpClient())
{
using (var response = await httpClient.GetAsync(url))
{
string apiResponse = await response.Content.ReadAsStringAsync();
results = JsonConvert.DeserializeObject(apiResponse);
}
}
return results;
}
This works. It calls the GetAll
https:
This works when calling GetById
https:
This does NOT work. I get a not found
https:
Can someone tell me what's wrong?
In theory, theory and practice are the same. But in practice, they never are.”
If it's not broken, fix it until it is.
Everything makes sense in someone's mind.
|
|
|
|
|
When you step through the Login code, what happens? The problem has to lie inside your repo.Login method, so that's the place you should be looking.
|
|
|
|
|
I guess what I'm asking is - isn't this the wrong way to pass params?
var url = $"https:// localhost:5001/api/User/Login/{userName}/{password}";
If so, that means I've set something up incorrectly. But I don't really know what.
In theory, theory and practice are the same. But in practice, they never are.”
If it's not broken, fix it until it is.
Everything makes sense in someone's mind.
|
|
|
|
|
Passing the credentials in the URL of a GET request is a very bad idea. You should only ever use a POST request.
With a GET request, you will end up with the credentials stored in plain-text in every log between you and the user, and in the browser history.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Hi forum,
What is currently the best method, in terms of security as well as scalability and least complexity, to store user uploaded documents on a shared hosting platform?
Is it to store the uploaded documents in a secure folder(s) location with a reference pointer (file path) in the database?
Or store the documents in the database itself (blob datatype)?
Or use a nosql "document store" version of the database?
The documents uploaded will be:
Mix of sensitive information (ex. containing a living person's date of birth) as well as historical, non-sensitive information
Varying in size from 1 page or image to several dozen
Varying in document type, mainly from .pdf, image files (.png, .jpeg, etc), .doc or .txt text files (there will be no audio or video file types)
The number of documents stored in the first year is estimated between 100 and 500, with about 1000 to 1200 additional each of the next couple of years.
If/when the site outgrows a shared hosting environment, other hosted solutions will be explored.
Other info:
PHP version 8.3.2
MySQL version 8.3.0 (InnoDB type used)
Thanks in advance!
modified 7-Mar-24 15:05pm.
|
|
|
|
|
I suggest you to stick with the former approach (storing files in a filesystem).
Storing large files in DB creates a lot of overhead when scanning table, inserting new rows, etc since such records span across multiple physical pages.
As a rule of thumb consider database for a structured data and filesystem or arbitrary unstructured files.
When it comes to NoSQL storages, most of the time you still expect the data there to conform to some schema. Their main use case is leverage horizontal scaling due to relaxed transactional guaranties (you can read more on a topic "CAP theorem" if you want to).
|
|
|
|
|
Thanks for the reply and information/suggestion. I appreciate it!
|
|
|
|
|
Bohdan Stupak wrote: Storing large files in DB creates a lot of overhead when scanning table, inserting new rows,
That is true.
But nothing in the OP suggests it will be close to that. The description suggests very few docs and the content of each is small. Plus one might also infer the churn rate is non-existent.
|
|
|
|
|
we5inelgr wrote: The number of documents stored in the first year is estimated between 100 and 500, with about 1000 to 1200 additional each of the next couple of years.
If/when the site outgrows a shared hosting environment
Those statements seem to be contradictory.
You are describing a very small data set. Unless your description is incorrect.
If you go up by an order of 10, and with 5 years the number of docs are 50,000. Which might seem like a bit but your other description suggests that the size of each is pretty small. But if each is a meg then at 50k it is 50 gig of data.
But my sizing might be way over. So if it is only about 6,000 and the size is 10k, then that is only 60 meg. Which is going to fit in anything that you might have.
we5inelgr wrote: in terms of security
Secure why? You mentioned birthday. If you are a business then you need all of that encrypted. But if this is just for you then is the only security that you want is that you don't loose it? If the second is true then you need two different ways to back it up. Online and local would be best.
|
|
|
|
|
The choice between storing files in a filesystem or as blobs in a database depends on various factors, where both approaches have their own pros and cons to consider.
Filesystem -
Pros-
Considered generally faster for read and write operations compared to databases.
Much easier to scale horizontally by adding more servers with shared access to the file system.
Cons-
Handling backups and recovery might be more complex especially if it grows over time.
Keeping file data and related metadata consistent can be challenging.
Database -
Pros-
Easier to maintain consistency between file data and metadata in a transactional database.
Database backups usually cover both file data and metadata.
Cons-
Retrieving and storing large files can impact database performance.
You may face scalability challenges when dealing with a large number of files.
|
|
|
|
|
iam looking for a working sample google maps on blazor web app with loading markers from database.
Using C# and SQL Server Database.
Everything i found i written for example with syncfusion or telerik controls.
or with old asp.net
could anyone help me?
|
|
|
|
|
That seems rather complicated to me. So less likely to find it as an example.
Following at least provides examples on how to use the google API itself.
google maps api markers
|
|
|
|
|
Hi jschell, thanks. But how to include in Blazor i found nothing too
|
|
|
|
|
Again the point is that you are looking for a complete solution for something that contains multiple pieces.
You must look for each piece then put them together.
|
|
|
|
|
I'm at the end of the project finally, and I'm putting the wraps on it.
I started programming headers in PHP for cache, and then it expanded into security as well. I built a system of ECMAScript modules, and my entry point module is being blocked by my CORS header. I can't figure this out, and could use some guidance on the subject.
Here is what I have.
/assets/scripts/core
/assets/scripts/core/coreExternal.module.js
coreExternal.module.js content
window.coreExternal {
setCommissionStartDate,
setCommissionStopDate, and so forth
On the WebPage, I use a script tag to load coreExternal
<script type="module" src="/pcad/assets/scripts/core/coreExternal.module.js"></script>
This call to the module, makes the window.coreExternal functions look like dangerous inlined script.
This is my PHP header for CORS
$nonce = base64_encode(random_bytes(16));
header("Content-Security-Policy: default-src 'self' *.fontawesome.com; script-src 'self' 'unsafe-inline' /pcad/assets/scripts/core/ https://kit.fontawesome.com/ 'nonce-".$nonce."' 'sha256-...'; style-src 'self'; img-src 'self' data:;");
From reading the documentation from Content Security Policy, I added 'unsafe-inline' which should sledge hammer out my modules, but they are still blocked.
Error Message:
Content-Security-Policy: The page’s settings blocked the loading of a resource at inline (“script-src”).
Source: coreExternal.setCommissionStartDate(this… assignCommission.phtml
My Questions
I don't do CORS stuff everyday, just once every few years, and this is the first time I've done it in code, and not used the web server to program this. Perhaps I have the concept going but failed in execution, well I'm sure that's it.
- Do I need the access-control headers?
- Did I paint myself into a corner using modules the way I did?
- Is one policy canceling another policy?
I still have issues with these error messages as well
Quote: Content-Security-Policy: The page’s settings blocked the loading of a resource at inline (“style-src”).
Source: --bs-breadcrumb-divider: '>'; viewVendors.phtml
The manual style I added to the table element
Quote: Content-Security-Policy: The page’s settings blocked the loading of a resource at inline (“style-src”).
Source: width: 100%; border: none; viewVendors.phtml
These are my headers in PHP. At this point, YES I am throwing darts at the wall on this, plus SMH and
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0, post-check=0, pre-check=0");
header("Pragma: no-cache");
header("Strict-Transport-Security: max-age=31536000; includeSubDomains; preload");
header("X-Content-Type-Options: nosniff");
header("X-Frame-Options: DENY");
header("X-XSS-Protection: 1; mode=block");
header('Referrer-Policy: same-origin');
header("Access-Control-Allow-Origin: self");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");
header("Access-Control-Expose-Headers: *");
header("Content-Security-Policy: default-src 'self' *.fontawesome.com; script-src 'self' 'unsafe-inline' /pcad/assets/scripts/core/ https://kit.fontawesome.com/ 'nonce-".$nonce."' 'sha256-...'; style-src 'self'; img-src 'self' data:;");
If it ain't broke don't fix it
Discover my world at jkirkerx.com
|
|
|
|
|
I replaced the script tags on the web pages to this ...
<?php $nonce = base64_encode(random_bytes(16)); ?>
<script type="module" src="/pcad/assets/scripts/core/core.module.js" nonce="<?php echo $nonce; ?>"></script>
So I don't have COR errors, I have Content-Security-Policy errors.
This error is from the input element onchange event, where I wasn't able to add an event listener, because of the data I needed to popular the function call. I'll have to rethink this.
Content-Security-Policy: The page’s settings observed the loading of a resource at inline (“script-src”). A CSP report is being sent.
Source: coreExternal.setCommissionFinishedDate(t… 72 assignCommission.phtml
OK, so this is not easy, and will require me to do way more research on the subject, and rethink some of the code in this project.
If it ain't broke don't fix it
Discover my world at jkirkerx.com
|
|
|
|
|
This is what is being outputed by the web server IIS server on server somnething version.
{
"name": "content-security-policy",
"value": "default-src 'self'; script-src 'self' swanpools-pcad-dev.occloud9.com; style-src 'self' 'unsafe-inline'"
},
Not even close to the header I wrote in PHP. I looked at IIS and didn't see any prepared headers. I'll dig down in PHP.ini and expand my search. And run the header in report only mode until I fix it. Chrome is telling me I'm in report only mode, but not Firefox.
If it ain't broke don't fix it
Discover my world at jkirkerx.com
|
|
|
|
|
I ended up with this, a compromise between using a hammer to nail it through with no more console errors, and fixing several security issues for the better. By hammering it, I can get the app running for the owner to evaluate and test, and then consider more security fixes and upgrades.
Font-Awesome or the FortAwesome free version
I removed all the Font-Awesome errors, but removing the all.min.js JavaScript file from the header elements. Turns out I don't need that JavaScript, and what it does is this.. Instead of using the fonts from Node_Modules, it fetches the latest version of the fonts and other stuff, to replace what Node_Modules has, and does things like monitor the use of the product, and causes licensing issues where it's no longer the free version. Well, the files it fetched were the free version files at least, so I got something right that I tossed in the trash.
Diagnostics
I used Mozilla FireFox at first, but it gave me generic information back, that never changed. I assume the headers I was inspecting was for public consumption. I ended up having to use Chrome in Developer mode, to see the real headers being returned from the response of the web page loading.
ECMA Script Modules
I used this to solve that issue in CSP. The use of a nonce. Declaring a master module that references child modules on a web page.
<?php $nonce = base64_encode(random_bytes(16)); ?>
script type="module" src="/assets/scripts/core/core.module.js" nonce="<?php echo $nonce; ?>"></script>
Inline scripts
I used this in the CSP rule below, to solve script within a element, calling onclick or onchange
script-src-elem 'self' 'unsafe-inline' 'unsafe-hashes';
onclick="core.setProjectType('<?php echo $apiUri; ?>', 'landscape')"
SVG like spinners and things you embed on the web page
img-src 'self' data: w3.org/svg/2000;
Warning
This is not my best work, and not completed yet, but gets the project back up and running so I can finish it and be done with it. This work does leave me with a little more work to beef up the security some more, but on my terms and not the web server or browsers terms.
If your clueless about this subject, then you can use this as a reference to model something for yourself. Remember I'm not an expert on this subject, but do understand the point. And I spent many hours doing research and reading, plus testing. It doesn't matter that this is PHP, because the principals are the same with most web technologies.
My Work
Cache Rules
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0, post-check=0, pre-check=0");
header("Pragma: no-cache");
X- Stuff Rules
header("Strict-Transport-Security: max-age=31536000; includeSubDomains; preload");
header("X-Content-Type-Options: nosniff");
header("X-Frame-Options: DENY");
header("X-XSS-Protection: 1; mode=block");
header('Referrer-Policy: same-origin');
COR Rules
header("Access-Control-Allow-Origin: <a href="https:
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");
header("Access-Control-Max-Age: 86400");
header("Access-Control-Expose-Headers: *");
CSP Rules
$nonce = base64_encode(random_bytes(16));
header("Content-Security-Policy: default-src 'self'; script-src 'self'; script-src-elem 'self' 'unsafe-inline' 'unsafe-hashes'; script-src-attr 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data: w3.org/svg/2000; object-src data: 'unsafe-eval';");
If it ain't broke don't fix it
Discover my world at jkirkerx.com
|
|
|
|
|
I'm following this tut on js: Arrow Functions JavaScript Tutorial - What NOT to do!!! , and in the part where he explains why not to use setTimeout inside arrow functions, the justification is that they look for scope on the window. and not on the enclosed scope of arrowFunc method. But the tests i made, had the opposite results: the named functions had window, arrow function had the correct one. So:
const dude = {
name: 'dude',
namedFunc() {
console.log('name 1: ', this.name);
setTimeout(function() {
console.log('this 1:', this);
console.log('name 2:', this.name);
}, 200);
},
arrowFunc() {
console.log('name 3:', this.name);
setTimeout(() => {
console.log('this 2:', this);
console.log('name 4:', this.name);
}, 300)
}
}
console.log('namedFunc:', dude.namedFunc());
console.log('arrowFunc:', dude.arrowFunc());
Expected:
this 1: {name: 'dude', namedFunc: ƒ, arrowFunc: ƒ}
name 2: dude
this 2: Window {window: Window, self: Window, document: document, name: '', location: Location, …}
name 4:
Actual result:
this 1: Window {window: Window, self: Window, document: document, name: '', location: Location, …}
name 2:
this 2: {name: 'dude', namedFunc: ƒ, arrowFunc: ƒ}
name 4: dude
modified 16-Jan-24 16:10pm.
|
|
|
|
|
Member 16183444 wrote: not to use setTimeout inside arrow function You say don't use setTimeout inside an arrow function, but your code example is using an arrow function inside setTimeout as a callback. That's the exact opposite. Do you have a timestamp in that video where he speaks of this?
Anyway, to your point, a lot of people get confused about this and lexical scope. I have no idea why there's so much disinformation in JavaScript's ecosystem. But alas, there is. When in doubt, trust what MDN says or, as in this case, your own testing.
From MDN: Arrow functions don't have their own bindings to this Which means, arrow functions don't bind their own scope. They inherit it from the parent one. A regular function will always define its this value. The value of this is determined by how a function is called. To put it simply, the this in the setTimeout function for the regular anonymous function is using the this of setTimeout 's scope because setTimeout is what calls the function.
Don't know what the dude said in the video because I didn't watch the whole 30 mins. But, that's the reason for the behavior you're seeing.
Jeremy Falcon
|
|
|
|
|