ASP .Net Core, Cors Host vs Origin - c#

I am new to ASP .NET.
When I Wanted to add Cors, there were 2 options. Host and Origin.
What is the difference between them?
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowOrigin", builder =>
{
builder
.AllowAnyMethod()
.AllowAnyHeader()
.SetIsOriginAllowed(origin => true)
.AllowCredentials();
//or
builder
.AllowAnyMethod()
.AllowAnyHeader()
.SetIsOriginAllowed((host) => true)
.AllowCredentials();
});
});

Those are both identical.
SetIsOriginAllowed expects a function that takes a string and returns a boolean.
Both of those lambdas do that.
You can call the parameter "x" and it'll still be the same function.

The method here is .SetIsOriginAllowed(Func<bool,string>).
It's one method that takes a lambda with a string parameter that returns a bool. If you're not familiar with lambdas, they can be thought of as really terse inline functions.
In your question, host and origin are just different names for that string parameter, you could call it TheSpanishInquisition and it would still work identically. If you're not actually using that parameter, I'd suggest using the _ discard operator, so it would be:
builder
.AllowAnyMethod()
.AllowAnyHeader()
.SetIsOriginAllowed(_ => true)
.AllowCredentials();
The different bracketisation doesn't matter either. Brackets around lambda parameters are optional if there's only a single parameter but are required if there are multiple.

You can give the parameter any name you want.They is no difference

Related

What alternatives can be used to represent .NET's 'from-end' indexer expression inside a lambda/expression tree?

I wrote a mock for a test which tries to mimic a method involving any file uploaded with a ".jpg" extension and decided to use .NET's 'from-end' indexer expression for convenience in checking if a file is indeed a JPEG file through the provided filename. However, the compiler complains with CS8790: An expression tree may not contain a pattern System.Index or System.Range indexer access. What alternatives I could use which achieves the same result/ease of use as the expression itself?
This code doesn't work:
_mock.Setup(f => f.DownloadFileAsync(
It.IsNotNull<Guid>(),
It.Is<string>(s => s.Split('.', StringSplitOptions.None)[^1] == "jpg"), // CS8790 Error
It.IsAny<CancellationToken>()))
.Returns(Task.FromResult(new BinaryData(Array.Empty<byte>())));
The code below works because it uses normal indexing:
_mock.Setup(f => f.DownloadFileAsync(
It.IsNotNull<Guid>(),
It.Is<string>(s => s.Split('.', StringSplitOptions.None)[1] == "jpg"), // compiles fine.
It.IsAny<CancellationToken>()))
.Returns(Task.FromResult(new BinaryData(Array.Empty<byte>())));

How to modify value being asserted inside of the config

I am wondering if there is a way to modify asserting value in the config.
For example,
I have the following assertion
customer.Should().Be(c, config => config.Excluding(c => c.Updated));
customer.Updated.Should().Be(c.Updated.ToString());
Is there any way to have conversion to string as part of the assertion instead of a separate assertion.
Something like this
customer.Should().Be(c, config => config.SomeFunction(c => c.Updated.ToString()))
According to the documentation here
Object graph comparison: Auto-Conversion
You should be able to instruct the assertion to
attempt to convert the value of a property of the subject-under-test to the type of the corresponding property on the expectation
customer.Should().BeEquivalentTo(c, options => options
.WithAutoConversionFor(x => x.Path.Contains("Updated")));
or
customer.Should().BeEquivalentTo(c, options => options.WithAutoConversion());

Disable AutoMapper built-in enum mapper

Is it possible to disable the built-in mapper for enums in AutoMapper, or replace it with one that always throws an exception?
I find the built in mapper to be highly unreliable as it will try it's best to map an input to any enum you give it which increases the risk of introducing, difficult to trace, bugs in your code.
I'd much rather have it fail with an exception telling me that I'm missing a mapper/converter than have it just work and then several steps down the call stack the code fails because the value isn't right in the current context.
Based on the comment from Lucian i added the following code to my configuration:
services.AddAutoMapper(config =>
{
var enumMapper = config.Mappers.Single(m => m is AutoMapper.Mappers.EnumToEnumMapper);
config.Mappers.Remove(enumMapper);
}, typeof(Startup));
This removes the default EnumToEnum mapper and gives me the exception when no mapping is configured.
From what you write I can think of a few options:
If you have an enum property on an object, you can ignore it
explicitly by using:
CreateMap<Foo, Bar>().ForMember(dest => dest.EnumProperty, opt => opt.Ignore());
If you create mappings for the properties you want to map and leave out the enum properties you can use:
CreateMap<Foo, Bar>().ForMember(...).ForAllOtherMembers(opt => opt.Ignore())
If you want to replace the mapping between to enum types you can overwrite it with:
Mapper.CreateMap<EnumSrc,EnumDst>().ConvertUsing(value => {
throw new Exception();
});

Registering types with lambda expression

I was wondering how do I achieve such a feature in the UnityContainer:
container.RegisterType<IDummy>(Func<IDummy>) // deferred resolution
If you're going to register factory instead of instance, try this:
container.RegisterType<IDummy>(new InjectionFactory(context => new Dummy()));
Just replace "context => new Dummy()" with your lambda.

Conditional Validation using Fluent Validation

What I need is a way to conditionally validate fields depending on if other fields are filled in.
Ex. I have a dropdown and a date field that are related. If none of the fields are set then the form should pass validation. However, if one of the two fields are set but the other isn't then the validation should fire, requiring the other field to be set.
I have written custom validation classes but it seems that it is validates on single fields. Is there a way to set up the validation that I need using the built in validators? If not, Is there a good way to connect two fields using a custom validator?
Fluent validation supports conditional validation, just use the When clause to check the value of the secondary field:
https://docs.fluentvalidation.net/en/latest/conditions.html
Specifying a condition with When/Unless The When and Unless methods can be used to specify conditions that control when the rule
should execute. For example, this rule on the CustomerDiscount
property will only execute when IsPreferredCustomer is true:
RuleFor(customer => customer.CustomerDiscount)
.GreaterThan(0)
.When(customer => customer.IsPreferredCustomer);
The Unless method is simply the opposite of When.
You may also be able to use the .SetValidator operation to define a custom validator that operates on the NotEmpty condition.
RuleFor(customer => customer.CustomerDiscount)
.GreaterThan(0)
.SetValidator(New MyCustomerDiscountValidator);
If you need to specify the same condition for multiple rules then you
can call the top-level When method instead of chaining the When call
at the end of the rule:
When(customer => customer.IsPreferred, () => {
RuleFor(customer => customer.CustomerDiscount).GreaterThan(0);
RuleFor(customer => customer.CreditCardNumber).NotNull();
});
This time, the condition will be applied to both rules. You can also
chain a call to Otherwise which will invoke rules that don’t match the
condition:
When(customer => customer.IsPreferred, () => {
RuleFor(customer => customer.CustomerDiscount).GreaterThan(0);
RuleFor(customer => customer.CreditCardNumber).NotNull();
}).Otherwise(() => {
RuleFor(customer => customer.CustomerDiscount).Equal(0);
});

Categories

Resources