MVC Web API - CORS Policy not working - asp.net-mvc

I have created a simple Web API in our existing MVC application (By adding an API controller). I hosted API to localhost and created an simple html page to call the service and to check CORS. To enable I changed my web.config file with following lines:
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
Everything was working fine and API was accessible through html page to localhost.
With same changes I hosted it on server (shared hosting server). It is throwing the same irritating error
XMLHttpRequest cannot load http://www.mywebsite.com/api/Booking. Invalid HTTP status code 405
According to search on Google it should work with these web.config changes. Please help to resolve the issue.
Thanks

Finally after spending a full day resolved the issue, followed link posted by "Yaser".
But I would say it is not easy that's why I am mentioning steps here.
First of all we need to install package through Nuget "Install-Package Microsoft.AspNet.WebApi.Cors" but if your target framework is 4.0 you cannot install it. First convert into 4.5 by right click on Project => Properties then in application tab select framework 4.5
The another gotcha is most of dll's will not work after changing framework version, again Right click on solution and select on Manage Nuget Package and update all. (take back up your project before doing this)
if everything works fine you are just one step away - add the following line in webapiconfig.cs under app_start folder
config.EnableCors();
After that open you API controller, add following line at controller level
[EnableCors(origins: "*", headers: "*", methods: "*")]
public class BookingController : ApiController
{
}
Last step change your web.config on production server add following line (compare with localhost web.config)
<dependentAssembly>
<assemblyIdentity name="System.Web.Http" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Net.Http.Formatting" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
</dependentAssembly>
All make a new build and replace all the bin files with new one ........ :)
Thanks

Related

Xamarin.Forms HttpClient to RESTful webservice

I have a Xamarin.Forms PCL application that access webservices via HttpClient. The app is working on Android but on iOS it doesn't connect to the webservices at all. Do I need to create a proxy for iOS and REST?
I have read the information here http://developer.xamarin.com/guides/cross-platform/application_fundamentals/web_services/ but frankly, it just confused me. I tried to create the proxy, as set out but it didn't work. I will persevere if it is necessary though.
I also tried HttpWebRequest method but wasn't successful with that either.
You only need to generate a proxy for WCF or SOAP. Rest should work just fine. This is how I implemented a GET to a REST service using HttpClient in a PCL.
using (var client = new HttpClient())
{
var result = await client.GetStringAsync(url);
return JsonConvert.DeserializeObject<Movie>(result);
}
Of course the other verbs take a little bit more work.
Do you perhaps need a binding redirect in the app.config? Check out this blog post about adding a redirect: http://motzcod.es/post/78863496592/portable-class-libraries-httpclient-so-happy.
Here is an example:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Net.Http" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="2.0.5.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>

Deploy WebSharper 2.4 sitelet on IIS7.5

I created a websharper sitelet project from Visual Studio 2012, which I called SiteletTest.
I compiled this project.
Then I copied SiteletTest/Web to inetpub/wwwroot.
Then I go to localhost/SiteletTest, localhost/SiteletTest/Home and localhost/SiteletTest/home but in each case I get http 404.
If I go to localhost/Main.html then I get a page, so going to this directory seems to work, but websharper doesn't appear to be working.
My web.config is below, and I have no idea what else to do. I already set the application pool to use .net 4:
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<authentication mode="Forms" />
<pages>
<controls>
<add tagPrefix="WebSharper" namespace="IntelliFactory.WebSharper.Web" assembly="IntelliFactory.WebSharper.Web" />
<add tagPrefix="ws" namespace="Website" assembly="Website" />
</controls>
</pages>
<httpModules>
<add name="WebSharper.Remoting" type="IntelliFactory.WebSharper.Web.RpcModule, IntelliFactory.WebSharper.Web" />
<add name="WebSharper.Sitelets" type="IntelliFactory.WebSharper.Sitelets.HttpModule, IntelliFactory.WebSharper.Sitelets" />
</httpModules>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules>
<add name="WebSharper.Remoting" type="IntelliFactory.WebSharper.Web.RpcModule, IntelliFactory.WebSharper.Web" />
<add name="WebSharper.Sitelets" type="IntelliFactory.WebSharper.Sitelets.HttpModule, IntelliFactory.WebSharper.Sitelets" />
</modules>
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
</assemblyBinding>
<assemblyBinding appliesTo="v4.0.30319" xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="FSharp.Core" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="2.0.0.0" newVersion="4.3.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
I am not going to be paying for a license until I get an idea if this may work for my needs, so, how do I get this to work?
I don't want to copy the sitelet code, but here are some fragments:
type Action =
| Home
| Contact
| Protected
| Login of option<Action>
| Logout
| Echo of string
and another fragment:
module Pages =
/// The home page.
let HomePage : Content<Action> =
Skin.WithTemplate "Home" <| fun ctx ->
[
H1 [Text "Welcome to our site!"]
"Let us know how we can contact you" => ctx.Link Action.Contact
]
I'm pretty sure you are missing 1 of three things:
1- Your sitelet/router isn't defined... something like this:
type Site() =
interface IWebsite<Action> with
member x.Sitelet =
Sitelet.Infer
<| function
| Home -> Pages.HomePage
...
member x.Actions = []
This maps each of the action cases to the correct page. There are many ways to define it but the above Sitelet.Infer will simply map the route by name.
2- You did not specify a Website assembly attribute... something like this:
[<assembly : Website(typeof<Site>)>]
do ()
I think this tells ASP.NET to load the above Sitelet as your site.
3- A third option is to automatically load a client-side JavaScript control from a Default.aspx page in the C# Web Project. If you use the Web Application (ASP.NET) template, you will see an example of that... but with that I do not think you can control the URL Path in a REST-full manner.

OpenID doesnt work with DotNetOpenAuth after upgrade to ver4

I have just upgraded my DotNetOpenAuth version from 3.4.7.11121 to 4.0.0.12079-RC1 to get support for OAuth2. The problem is that after the upgrade my OpenID-requests not longer works. The last row below generates a FileNotFoundException (Message=Could not load file or assembly 'System.Web.Mvc, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies.)
OpenIdRelyingParty openid = new OpenIdRelyingParty()
var request = openid.CreateRequest(requestedIdentifier, Realm.AutoDetect, returnUrl);
return request.RedirectingResponse.AsActionResult();
I can't really understand why it looks for that file. I use the DotNetOpenAuth library in a MVC3 application, and thus the 3.0-version of the System.Web.Mvc-file exists in the project.
Anyone that has any ideas what I can do to make it work?
Updated: The stable 4.0.0.12084 version was released a few hours after I posted this question. Have installed that instead of the RC, but it doesn't make any difference. I tried to install MVC ver 1.0 in order to get the required dll. After the installation no exception is thrown, but instead a white page containing the text "DotNetOpenAuth.Messaging.OutgoingWebResponseActionResult" is displayed instead of the redirect to the OpenID-service provider. I don't understand this..
//Per Andersson
Yeay, I found a solution. Just add a few lines in web.config
<runtime>
<legacyHMACWarning enabled="0" />
<!-- When targeting ASP.NET MVC 3, this assemblyBinding makes MVC 1 and 2 references relink
to MVC 3 so libraries such as DotNetOpenAuth that compile against MVC 1 will work with it. -->
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>

error with #MvcHtmlString.Create(...)) - system.web.mvc

I create a new asp.net mvc 4 version and
include dotnetopenauth implementation from Nerddinner project into it.
registration and authentication using formsauthentication works ok. On
the other hand when I include Logon details for openauth -
logonopenid.cshtml - implementation I received an error:
"Could not load file or assembly 'System.Web.Mvc, Version=1.0.0.0,
Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its
dependencies. The located assembly's manifest definition does not
match the assembly reference. (Exception from HRESULT: 0x80131040) "
Source Error:
Line 38: #MvcHtmlString.Create(Html.OpenIdSelectorScripts(options,
null))
I checked and I´m using system.web.mvc version= 4 and includes a
definition for mvchtmlstring and html helpers includes a definition
for openidselectorscripts. truly I dont know why is requesting
assembly 1.0.0.
any help will be appreciated. brgds,
sebastian.
You need to add this to your web.config file:
<runtime>
<!-- When targeting ASP.NET MVC 4, this assemblyBinding makes MVC 1 references relink
to MVC 4 so libraries such as DotNetOpenAuth that compile against MVC 1 will work with it. -->
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="4.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
sebastian_h,
I've seen this happening before. 'distant' memory recalls the issue being related to entries in the web.config that is located under the /Views folder (as opposed to the root web.config file).
I may be way off here, but this rings a bell. Certainly worth a quick peek.

ActionResult redirect renders using ToString()

Using the following sample: http://www.west-wind.com/Weblog/posts/899303.aspx
The following line...
return req.RedirectingResponse.AsActionResult();
renders the string "DotNetOpenAuth.Messaging.OutgoingWebResponseActionResult".
This is the class being returned as ActionResult in the line as posted. Does anyone know why I get the class name as string instead of a actual redirect?
Thnx in advance!
Could it be that you have multiple versions of MVC in your Bin directory and your web server? It strikes me that if you had multiple assemblies (different versions) of the MVC types like ActionResult loaded into your AppDomain, and the AsActionResult method returned one version and your MVC web app used a different version, that it might just bail out with a ToString. What version of ASP.NET MVC are you running? DotNetOpenAuth's AsActionResult method was compiled against the 1.0 RTM version of the MVC framework. If you're using ASP.NET MVC 2 (included with .NET 4.0), I could see this maybe being a problem.
I believe if you add this snippet to your MVC 2's web.config file, that it will allow you to use the official build of DotNetOpenAuth so you don't have to build your own:
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0" newVersion="2.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
Another solution, working for me with .Net 3.5 and MVC 2.
Instead of
var authRequest = relyingParty.CreateRequest(....);
....
return authRequest.RedirectingResponse.AsActionResult();
use
var authRequest = relyingParty.CreateRequest(....);
....
authRequest.RedirectToProvider();
Response.End();
return new EmptyResult();

Resources