Enabling CORS through Web.config vs WebApiConfig and Controller attributes - asp.net-web-api

There seems to be two functionally different ways to enable cross-origin request sharing in Web API 2.
One is to import System.Web.Http.Cors, decorate a controller with the EnableCors attribute and to write config.EnableCors() in the WebApiConfig:
[EnableCors(origins: "http://111.111.111.111", headers: "*", methods: "*")]
public class GenericController : ApiController
{
// etc.
The other is to modify the Web.config:
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="http://111.111.111.111" />
<add name="Access-Control-Allow-Methods" value="*" />
<add name="Access-Control-Allow-Headers" value="*" />
Is there a functional difference between these two different approaches? Which one is correct - don't these accomplish the same thing? If both methods are used to enable CORS, will things blow up?

If you add the headers to the web.config, every request that is served by that application will include the specified headers. This method is supported at the web server level and doesn't depend on config.EnableCors() being executed. You can use that method to add any HTTP header you want.
On the flip side, the EnableCors attribute requires WebAPI and you need to add some code to make it work. To the end user, the result is the same.
As for which way is better? I've liked keeping those settings in the application code by using the attribute so these settings are obvious to future developers. Depending on your needs, you may want to look into a abstract CorsApiController which your main ApiControllers could inherit to deliver the same CORS headers over and over. But this method won't work if the CORS headers need to vary from controller to controller or from action to action.

Related

How to access web API on client machine

I have hosted web API on Windows server 2012 . I set the binding like port and ipaddress.
After configuration, I browse the API and it's working fine.
Now I wanted to access my configured API from other machines.
What configuration I need to do in my web config.
I am beginner on deployment stuff. Please help me out on this.
Thanks in advance.
You may need to set Access-Control-Allow-Origin headers. Specifically for JSON:
[AllowCrossSiteJson]
public ActionResult YourMethod()
{
return Json("Works better?");
}
Or for a whole controller:
[AllowCrossSiteJson]
public class ValuesController : ApiController
{
You can also edit your web.config to include:
<httpProtocol>
<customHeaders>
<clear />
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
Source: https://learn.microsoft.com/en-us/aspnet/core/security/cors

When SimpleMembershipProvider is not the default provider

When you have multiple membership providers configured, like:
<membership defaultProvider="UmbracoMembershipProvider" userIsOnlineTimeWindow="15">
<providers>
<clear />
<add name="UmbracoMembershipProvider" type="umbraco.providers.members.UmbracoMembershipProvider" enablePasswordRetrieval="false" enablePasswordReset="false" requiresQuestionAndAnswer="false" defaultMemberTypeAlias="Another Type" passwordFormat="Hashed" />
<add name="UsersMembershipProvider" type="umbraco.providers.UsersMembershipProvider" enablePasswordRetrieval="false" enablePasswordReset="false" requiresQuestionAndAnswer="false" passwordFormat="Hashed" />
<add name="SimpleMembershipProvider" type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData"/>
</providers>
</membership>
Then let's say, for a particular section in the site I want to use SimpleMembershipProvider for auth (the rest of the site will use the default provider i.e. UmbracoMembershipProvider) ... Therefore I need to initialize SimpleMembership with:
WebSecurity.InitializeDatabaseConnection(
Constants.Membership.ConnectionStringName,
Constants.Membership.TableName,
Constants.Membership.UserIdColumnName,
Constants.Membership.UserNameColumnName,
false);
But it seems the above code only works when SimpleMembershipProvider is the defaultProvider. I can't see a way to specify the provider name I want to use? Is this even possible? Or does simplymembership assume you have one membership and role provider defined?
SimpleMembershipProvider is an implementation of ExtendedMembershipProvider. Although WebSecurity will work with any implementation of the extended provider it has some questionable coupling to SimpleMembershipProvider if used.
Basically SimpleMembershipProvider requires initialisation via WebSecurity, otherwise it will throw an exception when the extended membership interface is used. If not initialised then it wraps the default ASPNET provider and can be used with the original MembershipProvider Interface and old schema.
The initialisation routine only initialises the default providers, provided they can be cast to the simple provider implementations. So yes you cannot use SimpleMembershipProvider or SimpleRoleProvider unless they are configured as the default instances.
There's some more information about the limitations of SimpleMembershipProvider here.
There is a work-around. You can use reflection to temporarily swap the provider to the default during initialisation and then switch it back. See BetterMembership.Net for an example of doing exactly that. This library extends SimpleMembershipProvider specifically for use in multi-provider systems.
membershipProviderField = typeof(Membership)
.GetField("s_Provider", BindingFlags.NonPublic | BindingFlags.Static);
var originalMembershipProvider = membershipProviderField.GetValue(null);
membershipProviderField.SetValue(null, mySimpleMembershipProvider);
WebSecurity.InitializeDatabaseConnection(...)
membershipProviderField.SetValue(null, originalMembershipProvider);

Trying to enable client side validation in Orchard

I am trying to get client side validation enabled in Orchard for the comments. I have followed the advice in this SO discussion. I have commented out:
//ModelValidatorProviders.Providers.Clear();
//ModelValidatorProviders.Providers.Add(new LocalizedModelValidatorProvider());
I have included the following in Resource Manifest in the Comments Module.
manifest.DefineScript("jQueryValidation").SetUrl("jquery.validate.js", "jquery.validate.min.js").SetVersion("1.7").SetDependencies("jQuery");
manifest.DefineScript("jQueryValidation_Unobtrusive").SetUrl("jquery.validate.unobtrusive.js", "jquery.validate.unobtrusive.min.js").SetDependencies("jQuery", "jQueryValidation");
I stuck the following inthe view:
this.Script.Require("jQueryValidation_Unobtrusive").AtHead();
Also I added DataAnnotation to the CommentPartRecord.cs file, decorating Author with [Required]
And the changes to the Web.config:
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
And despite all of this server side valdiation for the Comments is whjat works. There is no client side validation.
The DataAnnotation should'nt be on CommentPartRecord but on CommentPart.
But Orchard.Comments is not a good example because CommentPart doesn't define the same properties than the Record (it will be refactored in a future version).
Try this on another module o one that you create.

Is it possible to get standard ASP.NET MVC Unobtrusive Validation to work in Orchard CMS?

I'm trying to build a custom module to integrate with Orchard CMS to implement a business application. While Orchard CMS is an MVC application, it doesn't seem possible (or, at least easy) to do all the things that can be done "out of the box" with MVC.
I'm trying to get unobtrusive validation to work on my view but can't seem to get this to work.
Update: As per Rohan West's advice below, I've now got the scripts included in the page using the ResourceManifest class and the Script.Require calls.
However, the validation attributes on the actual HTML elements are not being generated despite having the .NET attributes on my properties for which I'm using #Html.EditorFor on.
I have set the appSettings in the web.config file as follows:
<appSettings>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
<add key="webpages:Enabled" value="false" />
<add key="log4net.Config" value="Config\log4net.config" />
</appSettings>
Still no joy!
Update 2: As per Rohan West's suggestion, modifying the OrchardStarter class to comment out the following lines "solves" the problem:
ModelValidatorProviders.Providers.Clear();
ModelValidatorProviders.Providers.Add(new LocalizedModelValidatorProvider());
There should be a better way of handling this though.
You need to define the script in the resource manifest for your module.
public class ResourceManifest : IResourceManifestProvider
{
public void BuildManifests(ResourceManifestBuilder builder)
{
var manifest = builder.Add();
manifest.DefineScript("jQueryValidation").SetUrl("jquery.validate.js", "jquery.validate.min.js").SetVersion("1.7").SetDependencies("jQuery");
manifest.DefineScript("jQueryValidation_Unobtrusive").SetUrl("jquery.validate.unobtrusive.js", "jquery.validate.unobtrusive.min.js").SetDependencies("jQuery", "jQueryValidation");
}
}
and then in your page
#{
this.Script.Require("jQueryValidation_Unobtrusive").AtHead();
}
Have a look at the following class
Orchard.Environment.OrchardStarter
In Orchard 1.4.2 there is a line which removes all ModelValidatorProviders
ModelValidatorProviders.Providers.Clear();
This is removing the default DataAnnotationsModelValidatorProvider from the collection.
You could try adding it to the collection,

Set connectionstring for Membership Service via code

I have an ASP.NET web project and a membership provider configured via my web.config. Its fully working so no problem there.
We have an older system with a lot of users and I would therefor like to create a class library that can create users in this ASP.NET project but since its a class library it cannot have its own app.config-file.
is it possible to set all this information via code somehow?
<membership defaultProvider="ShidMembershipProvider">
<providers>
<clear/>
<add name="ShidMembershipProvider" type="SundaHus.AspNet.Membership.ShidMembershipProvider" connectionStringName="ShidConnectionString" enablePasswordRetrieval="true" enablePasswordReset="true" requiersQuestionAndAnswer="true" applicationName="ECB3-development" minRequiredPasswordLength="5"/>
</providers>
</membership>
You have a custom membership provider it looks like? This connects to your own custom database? You should be able to just point to that database for your code. Or, if you just inherit the functionality from the base class, you can also try overriding the Initialize method, look for the connection string, and change the value to something else.

Resources