Can not upload image to API with Postman (File field is required) .NET6 - postman

I am trying to send an image file to api controller with postman. I am working with .Net 6.
The problem is an error always appears as in the image, postman screenshot
That is my code
namespace WebAPI.Controllers
public class Image
{
public IFormFile file { get; set; }
}
[Route("api/[controller]")]
[ApiController]
public class CarImagesController : ControllerBase
{
[HttpPost("add")]
public IActionResult Add([FromForm] Image file)
{
if (file != null)
{
return Ok();
}
return BadRequest();
}
}
If it is eligible to use, I want to change argument of Add method, i mean
public IActionResult Add([FromForm] IFormFile file)
and I want to delete Image class after that change.
Thanks for your help

Your code is correct, I create a sample using them, they all works well. The issue might relate that when using Postman, the key value contains spaces, such as file .
You can check the following screenshot: when using file key, everything works well, but if using file (with spaces), it will show the 400 error.

your code is all fine but you have an issue in postman. Check the formField key file. It has whitespace bcz you pressed enter there. Just remove any extra space and it should work.
I know it sounds stupid, but that's the issue. Postman takes whitespace and new lines seriously as key and values.
see the arrow and ... , that's the indicator.

Related

cross site scripting issues with Fullwidth unicode characters

I have developed an application in Asp.net mvc 5.I am facing cross site scripting issues with Full width unicode characters.
Attack value:-%uff1cinput/onclick=alert(1)%uff1e
%uff1c = <
%uff1e = >
I know Antixss library can be used to resolve the issue.But anybody can show a sample code on how to implement Antixss for input filtering and output encoding
Please suggest a solution for this.
I had the same issue, and finally found a fix for it. Hopefully this will help anyone else that has the same problem.
Basically, you need to extend the RequestValidator base class that's part of System.Web.Util. Here's my class that will filter out both the unicode values and the actual full width less than and greater than symbols:
using System.Web;
using System.Web.Util;
namespace Common.Extensions
{
public class RequestValidatorExtension : RequestValidator
{
private const string UNICODE_LESS_THAN = "%uff1c";
private const string UNICODE_GREATER_THAN = "%uff1e";
public RequestValidatorExtension() { }
protected override bool IsValidRequestString(
HttpContext context,
string value,
RequestValidationSource requestValidationSource,
string collectionKey,
out int validationFailureIndex
)
{
validationFailureIndex = -1;
if (value.Contains(UNICODE_LESS_THAN))
value = value.ReplaceWith(UNICODE_LESS_THAN, "<");
else if (value.Contains("<"))
value = value.ReplaceWith("<", "<");
if (value.Contains(UNICODE_GREATER_THAN))
value = value.ReplaceWith(UNICODE_GREATER_THAN, ">");
else if (value.Contains(">"))
value = value.ReplaceWith(">", ">");
return base.IsValidRequestString(context, value, requestValidationSource, collectionKey, out validationFailureIndex);
}
}
}
In my case, when the "malicious" code was added into a text box, it would be passed in as the unicode value. However, when the query string was intercepted by Fiddler and modified, the value would be in the full width symbol. That is why there's a check for both.
You also have to register this new RequestValidationType in the web.config or in your global.asax page. Here's an example of both:
// Web.config
<httpRuntime requestValidationMode="2.0" requestValidationType="namespace.class" />
// Global.asax.cs
protected void Application_Start(object sender, EventArgs e)
{
RequestValidator.Current = new RequestValidatorExtension();
}
Also, here's a link to the MS documentation on how to utilize and extend the class.
Hope this helps, cheers!
Based on the Article below, the issue happened because the SQL server will try to convert the Unicode <> to Ascii version of <> if your database column dost not support nvarchar or nchar. As a result, when the same <> are queried from the database, it becomes XSS injection.
So essentially there are two ways to fix this.
1st as #Alec Zorn's answer, you can block them at input. This is a simple and effective approach.
The 2nd approach is you can change the DB column to use nvarchar or nchar. But this approach will require you to change a lot of columns.
https://www.gosecure.net/blog/2016/03/22/xss-for-asp-net-developers/

How to attach Sitecore context for controller action mappled to route robots.txt?

In Sitecore I'm trying to set up a way for our client to modify the robots.txt file from the content tree. I am attempting to set up a MVC controller action that is mappled to route "robots.txt" and will return the file contents. My controller looks like this:
public class SeoController : BaseController
{
private readonly IContentService _contentService;
private readonly IPageContext _pageContext;
private readonly IRenderingContext _renderingContext;
public SeoController(IContentService contentService, IPageContext pageContext, IRenderingContext renderingContext, ISitecoreContext glassContext)
: base(glassContext)
{
_contentService = contentService;
_pageContext = pageContext;
_renderingContext = renderingContext;
}
public FileContentResult Robots()
{
string content = string.Empty;
var contentResponse = _contentService.GetRobotsTxtContent();
if (contentResponse.Success && contentResponse.ContentItem != null)
{
content = contentResponse.ContentItem.RobotsText;
}
return File(Encoding.UTF8.GetBytes(content), "text/plain");
}
}
And the route config:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
RouteTable.Routes.MapRoute("Robots.txt", "robots.txt", new { controller = "Seo", action = "Robots" });
}
}
This all works great if I use a route without the ".txt" extension. However after adding the extension I get a null reference exception in the domain layer due to the context database being null. Here's where the error happens:
public Item GetItem(string contentGuid)
{
return Sitecore.Context.Database.GetItem(contentGuid);
}
I'm assuming that there is a setting in sitecore that ignores the .txt extension. I've tried adding it as an allowed extension in the Sitecore.Pipelines.PreprocessRequest.FilterUrlExtensions setting of the config. Is there anything else I could be missing?
Ok, I found the issue. I was correct in assuming that txt needed to be added to the allowed extensions for the Sitecore.Pipelines.PreprocessRequest.FilterUrlExtensions setting. However robots.txt was listed under the IgnoreUrlPrefixes setting in the config file. That was causing sitecore to ignore that request. I removed it from that list and it's working great now.
This is a pure guess, but you might also have to add it to the allowed extensions of Sitecore.Pipelines.HttpRequest.FilterUrlExtensions in httpRequestBegin as well.

encodeNameReplacements not working in page editor

The sitecore configuration code below works well in normal mode.
<encodeNameReplacements>
<replace mode="on" find=" " replaceWith="-" />
</encodeNameReplacements>
In Page editor mode the (Spaces) " " or not replaced with "-".
In Page Editor Mode:
If i try to remove image and insert new one; image is not displayed until i saved the page because the (Spaces) " " or not replaced with "-".
Am i missing anything, any ideas will be appreciated.
I had a problem with the encodeNameReplacements messing up the media paths until I found this article.
After implementing this code in our project a dash will replace the %20 and the media images will still render.
Sitecore 7.2 Upgrade Media Library Gotcha
http://getfishtank.ca/blog/sitecore-7-2-upgrade-encoding-media-library-item-names
While upgrading a client to Sitecore 7.2 this section of the release notes gave us pause:
Media API
When rendering media URLs, the system did not use the configuration in the encodeNameReplacements section to replace special characters in the URLs.
This has been fixed so that media URLs also use the encodeNameReplacements configuration. (323105, 314977)
Summary:
media library URLs now use the encodeNameReplacements configuration.
If any one run into this problem; Look for any custom media code written on your site. I got the below custom code causing the problem:
public class MediaProvider : Sitecore.Resources.Media.MediaProvider
{
public override string GetMediaUrl(Sitecore.Data.Items.MediaItem item, Sitecore.Resources.Media.MediaUrlOptions options)
{
string url = base.GetMediaUrl(item, options);
if (!(Sitecore.Context.PageMode.IsNormal && options.UseItemPath))
{
return url;
}
}
}
Working when Changed to
public class MediaProvider : Sitecore.Resources.Media.MediaProvider
{
public override string GetMediaUrl(Sitecore.Data.Items.MediaItem item, Sitecore.Resources.Media.MediaUrlOptions options)
{
string url = base.GetMediaUrl(item, options);
if (options.UseItemPath)
{
return url;
}
}
}

Login only prestashop catalog

Im building a prestashop catalog, but it needs to be visible to logged in customers only. Is this possible. It would be nice if the built in prestashop login is used for this.. any help is appreciated.
I have a suggestion. You can use the Customer Groups feature in PrestaShop 1.5 and only allow logged in customers to see the prices. For every Customer that is grouped in Visitor, they would see your website in Catalog Mode.
Prestashop 1.5 solution:
Simply upload the original file:
classes\controller\FrontController.php
into:
override/classes/controller/FrontController.php
Next, rename the class. Final code should look like this:
class FrontController extends FrontControllerCore
{
public function init()
{
parent::init();
if (!$this->context->customer->isLogged() && $this->php_self != 'authentication' && $this->php_self != 'password')
{
Tools::redirect('index.php?controller=authentication?back=my-account');
}
}
}
The last step is to manually delete the following file so prestashop is aware of the overriden class (It will be re-generated automatically):
cache/class_index.php
And voilà, functionality achieved without overwriting core files.
It'll be easy.
Use this code:
if(!self::$cookie->isLogged(true) AND in_array($this->step, array(1, 2, 3)))
Tools::redirect('authentication.php');
In the preprocess of your indexController
Here’s my solution, it works like a charm and is a very easy fix!
In classes\Configuration.php (around line 114) it looks like this
static public function get($key, $id_lang = NULL)
{
if ($id_lang AND isset(self::$_CONF_LANG[(int)$id_lang][$key]))
return self::$_CONF_LANG[(int)$id_lang][$key];
elseif (is_array(self::$_CONF) AND key_exists($key, self::$_CONF))
return self::$_CONF[$key];
return false;
}
change it to this:
static public function get($key, $id_lang = NULL)
{
//Grab access to the $cookie which is already loaded in the FrontController as global $cookie;
global $cookie;
if ($id_lang AND isset(self::$_CONF_LANG[(int)$id_lang][$key]))
return self::$_CONF_LANG[(int)$id_lang][$key];
elseif (is_array(self::$_CONF) AND key_exists($key, self::$_CONF))
//If the system is trying to find out if Catalog Mode is ON, then return the configuration setting,
//but override it with the user logon status
if($key == 'PS_CATALOG_MODE')
{
return !$cookie->logged || self::$_CONF[$key];
}
else
{
return self::$_CONF[$key];
}
return false;
}
Essentially, I wanted to force the system to display the “Catalog Mode” when the user is not logged in, and to turn this off when he is logged in.
I can guarantee this works for v1.4.3.0 and the code for the current version 1.4.8.2 (at the time of this post) has not changed, so it should work there.

Is it possible to create an email-attachment on a Silverlight email?

I need to be able to send an email from a silverlight client-side application.
I've got this working by implementing a webservice which is consumed by the application.
The problem is that now I need to be able to add an attachment to the emails that are being sent.
I have read various posts, tried a dozen times to figure it out by myself, but to no prevail.
So now I find myself wondering if this is even possible?
The main issue is that the collection of attachments needs to be serializable. So, going by this, ObservableCollection - of type(FileInfo) is not working, ObservableCollection - of type (object) is not working... I've tried using List - of type(Stream), which serializes, but then i do not know how to create the file on the webservice side, as the stream-object does not have a name (which is the first thing I tried to assign to the Attachment object which will then be added to the message.attachments)... I'm kind of stuck in a rut here.
Can anybody maybe shed some light on this please?
I figured out how to do this, and it wasn't really as difficult as it appeared.
Create the following in your webservice-namespace:
`
[Serializable]
public class MyAttachment
{
[DataMember]
public string Name { get; set; }
[DataMember]
public byte[] Bytes { get; set; }
}`
Then add the following to your web-method parameters:
MyAttachment[] attachment
Add the following in the execution blocks of your web-method:`
foreach (var item in attachment)
{
Stream attachmentStream = new MemoryStream(item.Bytes);
Attachment at = new Attachment(attachmentStream, item.Name);
msg.Attachments.Add(at);
}`
Create the following property (or something similar) at your client-side:
`
private ObservableCollection<ServiceProxy.MyAttachment> _attachmentCollection;
public ObservableCollection<ServiceProxy.MyAttachment> AttachmentCollection
{
get { return _attachmentCollection; }
set { _attachmentCollection = value; NotifyOfPropertyChange(() => AttachmentCollection); }
}`
New up the public property (AttachmentCollection) in the constructor.
Add the following where your OpenFileDialog is supposed to return files:`
if (openFileDialog.File != null)
{
foreach (FileInfo fi in openFileDialog.Files)
{
var tempItem = new ServiceProxy.MyAttachment();
tempItem.Name = fi.Name;
var source = fi.OpenRead();
byte[] byteArray = new byte[source.Length];
fi.OpenRead().Read(byteArray, 0, (int)source.Length);
tempItem.Bytes = byteArray;
source.Close();
AttachmentCollection.Add(tempItem);
}
}`
Then finally where you call your web-method to send the email, add the following (or something similar):
MailSvr.SendMailAsync(FromAddress, ToAddress, Subject, MessageBody, AttachmentCollection);
This works for me, the attachment is sent with the mail, with all of its data exactly like the original file.