I'm using AttributeRouting with my Web API (MVC 4).
Why does this work?
[AcceptVerbs("PUT")]
[PUT("api/v1/tokens/current")]
public MemoryToken UpdateToken([FromBody] DeviceTokenViewModel viewModel)
{...}
And this one does not?
[PUT("api/v1/tokens/current")]
public MemoryToken UpdateToken([FromBody] DeviceTokenViewModel viewModel)
{...}
Error message: The requested resource does not support http method "PUT".
Why do I have to explicitly accept the PUT verb?
I'm just confused because something similar with POST works just fine (I don't have to specify the accepted verbs):
[POST("api/v1/tokens")]
public MemoryToken CreateToken()
{...}
From various other posts I believe it has to do with the setting in my web.config. The web server section currently looks like this:
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules runAllManagedModulesForAllRequests="true" />
<handlers>
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
<add name="AttributeRouting" path="routes.axd" verb="*" type="AttributeRouting.Web.Logging.LogRoutesHandler, AttributeRouting.Web" />
</handlers>
I tried a couple things like removing WebDav and stuff. But nothing worked so far (unless explicitly allowing the PUT verb in the annotation).
Oh, I am using Visual Studios built-in development server.
Thanks guys!
In this link they describe the POST method as being the default if none of the actions match. So that's why it still works for your CreateToken() method without an HttpPost attribute .
You can specify the HTTP method with an attribute: AcceptVerbs, HttpDelete, HttpGet, HttpHead, HttpOptions, HttpPatch, HttpPost, or HttpPut.
Otherwise, if the name of the controller method starts with "Get", "Post", "Put", "Delete", "Head", "Options", or "Patch", then by convention the action supports that HTTP method.
If none of the above, the method supports POST.
Related
I am trying to make an HTTP PUT with an integer parameter to a MVC WebApi.
I tried to follow the angular 2 guidelines for HTTP PUT: https://angular.io/docs/ts/latest/guide/server-communication.html
My WebApi:
public IHttpActionResult Put([FromBody]int id)
{
return Ok();
}
My Http PUT in my service in my ionic 2 app:
makePut(){
let body = JSON.stringify({id:155320});
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return new Promise(resolve => {
this.http.put('API_URL', body, options)
.subscribe(
response => {
console.log(response.text());
},
error => {
//Failed to Login.
alert(error.text());
console.log(error.text());
});
});
}
And finally the call to my service from my home page:
this.service.makePut().then(data => {console.log(data);});
When I run this I get a 405 method not allowed. Is there anything I am missing?
UPDATE here is part of the web.config in my web api:
<system.webServer>
<security>
</security>
<validation validateIntegratedModeConfiguration="false" />
<modules runAllManagedModulesForAllRequests="true">
<remove name="WebDAVModule" />
</modules>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
</customHeaders>
</httpProtocol>
<handlers>
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
It might be Web Api error and you can resolve that by adding this code to your web.config file
<handlers accessPolicy="Read, Script">
<remove name="WebDAV" />
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit"
path="*."
verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS"
modules="IsapiModule"
scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll"
preCondition="classicMode,runtimeVersionv4.0,bitness64"
responseBufferLimit="0" />
this article can give you more information about 405 error.
I was able to fix the problem, which turned out to be a CORS issue. You can view how to disable same origin policy in Chrome here: How to resolve CORS issue and JSONP issue in Ionic2
Once I disabled it in chrome, the HTTP PUT succeed.
Here is my final code:
makePut(){
let body = 155320; // this is different
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return new Promise(resolve => {
this.http.put('API_URL', body, options)
.subscribe(
response => {
console.log(response.text());
},
error => {
//Failed to Login.
alert(error.text());
console.log(error.text());
});
});
}
I installed elmah as described here https://github.com/rdingwall/elmah-contrib-webapi
Now I am trying to access the logging but I keep getter error 404 errors.
Am I using the correct url ? Is there still some configuration missing ?
My webapi runs as follows :
http://localhost/MagnusREST/api/Customers/054036?frmt=xml
My application_start looks like this :
protected void Application_Start()
{
GlobalConfiguration.Configuration.Filters.Add(new ElmahHandleErrorApiAttribute()); //added for elmah
AreaRegistration.RegisterAllAreas();
UnityConfig.RegisterComponents();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
my webapi config remained unchanged and looks like this :
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Formatters.JsonFormatter.MediaTypeMappings.Add(
new QueryStringMapping("frmt", "json",
new MediaTypeHeaderValue("application/json")));
config.Formatters.XmlFormatter.MediaTypeMappings.Add(
new QueryStringMapping("frmt", "xml",
new MediaTypeHeaderValue("application/xml")));
//config.Formatters.Clear();
JsonMediaTypeFormatter oldformatter = config.Formatters.Where(f => f is JsonMediaTypeFormatter).FirstOrDefault() as JsonMediaTypeFormatter;
if (oldformatter != null) config.Formatters.Remove(oldformatter);
config.Formatters.Insert(0,new PartialJsonMediaTypeFormatter() { IgnoreCase = true });
}
}
Accessing logs via http://localhost/MagnusREST/api/elmah.axd does not work, via http://localhost/MagnusREST/elmah.axd does not work and http://localhost/elmah.axd does not work either.
What am I doing wrong?
This is running in visual studio 2013.
There was a missing piece in the web.config
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
<add name="elmah" verb="POST,GET,HEAD" path="elmah.axd" type="Elmah.ErrorLogPageFactory, Elmah" />
</handlers>
The elma handler needs to be added. After doing that I could access the elmah log using followin url :
http://localhost/MagnusREST/elmah.axd
You have to read the documentation and questions both for elmah and the webapi contrib it seems. Ok the first problem is passed, what will be the next ;-)
To get is fully working more is needed than the above
Add configsections
<configSections>
<sectionGroup name="elmah">
<section name="security" requirePermission="false" type="Elmah.SecuritySectionHandler, Elmah"/>
<section name="errorLog" requirePermission="false" type="Elmah.ErrorLogSectionHandler, Elmah" />
<section name="errorMail" requirePermission="false" type="Elmah.ErrorMailSectionHandler, Elmah" />
<section name="errorFilter" requirePermission="false" type="Elmah.ErrorFilterSectionHandler, Elmah"/>
</sectionGroup>
</configSections>
Add the elmah configuration you like for instance to send mails :
<elmah>
<security allowRemoteAccess="0" />
<errorMail from="xxxx" to="xxx" subject="some error" async="true"
smtpPort="25" smtpServer="xxx" userName="xxx" password="xxx"/>
</elmah>
The system.web and system.webserver need to be something like this :
<system.web>
<compilation debug="true" targetFramework="4.5.1" />
<httpRuntime targetFramework="4.5.1" />
<httpHandlers>
<add verb="POST,GET,HEAD" path="elmah.axd" type="Elmah.ErrorLogPageFactory, Elmah" />
</httpHandlers>
<httpModules>
<add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah"/>
<add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah"/>
</httpModules>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules>
<add name="Elmah.ErrorLog" type="Elmah.ErrorLogModule, Elmah" preCondition="managedHandler" />
<add name="Elmah.ErrorMail" type="Elmah.ErrorMailModule" preCondition="managedHandler" />
</modules>
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
<add name="elmah" verb="POST,GET,HEAD" path="elmah.axd" type="Elmah.ErrorLogPageFactory, Elmah" />
</handlers>
</system.webServer>
Take a good look where elmah is being mentioned and add those things to your own configuration file that might look slightly different.
I also had to add this to my web.config and they it worked
<location path="elmah.axd" inheritInChildApplications="false">
<system.web>
<httpHandlers>
<add verb="POST,GET,HEAD" path="elmah.axd" type="Elmah.ErrorLogPageFactory, Elmah" />
</httpHandlers>
<!--
See http://code.google.com/p/elmah/wiki/SecuringErrorLogPages for
more information on using ASP.NET authorization securing ELMAH.
<authorization>
<allow roles="admin" />
<deny users="*" />
</authorization>
-->
</system.web>
<system.webServer>
<handlers>
<add name="ELMAH" verb="POST,GET,HEAD" path="elmah.axd" type="Elmah.ErrorLogPageFactory, Elmah" preCondition="integratedMode" />
</handlers>
</system.webServer>
I have an ASP.NET WebForms app that is widely distributed. My new version adds Web.API and users have been playing with a beta. In most beta installations everything works fine, but for some installs all the Web.API calls return HTTP 404 Not Found errors. I can't figure out why the Web.API calls fail on some servers but works fine on others.
My guess is there is some kind of server configuration that is breaking the routing, but I can't figure out what it is. I've even RDP'd into one of these sites and can't find anything obvious.
This is an example API call:
GET http://site.com/api/events/27
The code:
namespace GalleryServerPro.Web.Api
{
public class EventsController : ApiController
{
public string Get(int id)
{
return "Event data for ID " + id;
}
}
}
The route definitions, which are called from the Init event of a custom HTTP module named GspHttpApplication:
private void RegisterRoutes(RouteCollection routes)
{
routes.MapHttpRoute(
name: "GalleryApi1",
routeTemplate: "api/{controller}"
);
routes.MapHttpRoute(
name: "GalleryApi2",
routeTemplate: "api/{controller}/{id}",
defaults: new { },
constraints: new
{
id = #"\d*",
}
);
routes.MapHttpRoute(
name: "GalleryApi3",
routeTemplate: "api/{controller}/{id}/{action}",
defaults: new
{
},
constraints: new
{
id = #"\d*"
}
);
// Add route to support things like api/meta/galleryitems/
routes.MapHttpRoute(
name: "GalleryApi4",
routeTemplate: "api/{controller}/{action}",
defaults: new
{
},
constraints: new
{
}
);
}
The example GET above should match the route named GalleryApi2, and like I said in most installations it does.
I know WebDAV can cause trouble (405 errors), so I already remove it in web.config:
<system.webServer>
<modules>
<remove name="WebDAVModule" />
<add name="GspApp" type="GalleryServerPro.Web.HttpModule.GspHttpApplication, GalleryServerPro.Web" />
</modules>
<handlers>
<remove name="WebDAV" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
...
</system.webServer>
So it all comes down to figuring out why this configuration works for some web installs and not others.
Roger
I am making a Helper with razor generator to build a cutom control in which there will be two radio buttons (yes/no)
I want to use Html.BeginForm for this.
But can't do it.
Do you know how to do it or another way to do it ?
Thanks.
Edit :
When I put this code
#using (Html.BeginForm()) {
<input type="radio"/>
<input type="radio"/>
}
I get this error
'System.Web.WebPages.HtmlHelper' does not contain a definition for BeginForm and no extension method
'BeginForm' accepting a first argument of type 'System.Web.WebPages.Html.HtmlHelper'could be found
It's most likely a namespacing or reference issue.
First, check to make sure that System.Web.WebPages shows up in your project references. Then add
#using System.Web.WebPages
to the top of your view. If that fixes it, you can move the reference into the web.config per this answer on the same type of topic
Add this code to your helper function when your helper functions are located in the App_Code folder.
var Html = ((System.Web.Mvc.WebViewPage)WebPageContext.Current.Page).Html;
var Ajax = ((System.Web.Mvc.WebViewPage)WebPageContext.Current.Page).Ajax;
Don't forget to include the right namespaces in the file: #using ....
For me it was a missing namespace, yes, but not the one mentioned by eouw0o83hf:
#using System.Web.Mvc.Html;
Please post your code when you ask a question so we can see what you're doing wrong. Try this:
#using (Html.BeginForm()) {
<input type="radio"/>
<input type="radio"/>
}
I ran into the same issue and just solved it. I changed version in the web.config file under the views folder.
Here is my previous code
<system.web.webPages.razor>
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, **Version=5.0.2.2**, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<pages pageBaseType="System.Web.Mvc.WebViewPage">
<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Optimization"/>
<add namespace="System.Web.Routing" />
<add namespace="CMSSol" />
</namespaces>
</pages>
and here is my new code
<system.web.webPages.razor>
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, **Version=5.0.0.0**, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<pages pageBaseType="System.Web.Mvc.WebViewPage">
<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Optimization"/>
<add namespace="System.Web.Routing" />
<add namespace="CMSSol" />
</namespaces>
</pages>
When my Razor view calls #Html.OpenIdSelector(... I get an InvalidOperationException:
The current IHttpHandler is not one of
types: System.Web.UI.Page,
DotNetOpenAuth.IEmbeddedResourceRetrieval.
An embedded resource URL provider must
be set in your .config file.
What exactly should I set in the config file?
Just NuGet the DotNetOpenAuth package. It will setup everything you need in your config file:
Right click on the References of your web project in the solution explorer
Add Library Package Reference...
Click on the Online tab.
In the search box type dotnetopenauth
Click Install
Everything will be automatically setup and the correct assemblies will be downloaded from the internet and added as reference.
Here's how the web.config file looks like after performing this:
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=152368
-->
<configuration>
<configSections>
<section name="uri" type="System.Configuration.UriSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<section name="dotNetOpenAuth" type="DotNetOpenAuth.Configuration.DotNetOpenAuthSection" requirePermission="false" allowLocation="true" />
</configSections>
<connectionStrings>
<add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient" />
</connectionStrings>
<appSettings>
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</assemblies>
</compilation>
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="2880" />
</authentication>
<membership>
<providers>
<clear />
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
</providers>
</membership>
<profile>
<providers>
<clear />
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/" />
</providers>
</profile>
<roleManager enabled="false">
<providers>
<clear />
<add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/" />
<add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />
</providers>
</roleManager>
<pages>
<namespaces>
<add namespace="System.Web.Helpers" />
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
<add namespace="System.Web.WebPages" />
</namespaces>
</pages>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules runAllManagedModulesForAllRequests="true" />
</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" />
<bindingRedirect oldVersion="1.0.0.0" newVersion="2.0.0.0" />
</dependentAssembly>
</assemblyBinding>
<legacyHMACWarning enabled="0" />
</runtime>
<uri>
<!-- The uri section is necessary to turn on .NET 3.5 support for IDN (international domain names),
which is necessary for OpenID urls with unicode characters in the domain/host name.
It is also required to put the Uri class into RFC 3986 escaping mode, which OpenID and OAuth require. -->
<idn enabled="All" />
<iriParsing enabled="true" />
</uri>
<system.net>
<defaultProxy enabled="true" />
<settings>
<!-- This setting causes .NET to check certificate revocation lists (CRL)
before trusting HTTPS certificates. But this setting tends to not
be allowed in shared hosting environments. -->
<!--<servicePointManager checkCertificateRevocationList="true"/>-->
</settings>
</system.net>
<dotNetOpenAuth>
<!-- This is an optional configuration section where aspects of dotnetopenauth can be customized. -->
<!-- For a complete set of configuration options see http://www.dotnetopenauth.net/developers/code-snippets/configuration-options/ -->
<openid>
<relyingParty>
<security requireSsl="false" />
<behaviors>
<!-- The following OPTIONAL behavior allows RPs to use SREG only, but be compatible
with OPs that use Attribute Exchange (in various formats). -->
<add type="DotNetOpenAuth.OpenId.Behaviors.AXFetchAsSregTransform, DotNetOpenAuth" />
</behaviors>
</relyingParty>
</openid>
<messaging>
<untrustedWebRequest>
<whitelistHosts>
<!-- Uncomment to enable communication with localhost (should generally not activate in production!) -->
<!--<add name="localhost" />-->
</whitelistHosts>
</untrustedWebRequest>
</messaging>
<!-- Allow DotNetOpenAuth to publish usage statistics to library authors to improve the library. -->
<reporting enabled="true" />
</dotNetOpenAuth>
</configuration>
UPDATE:
You could implement a custom resource retrieval provider:
public class CustomResourceProvider : IEmbeddedResourceRetrieval
{
public Uri GetWebResourceUrl(Type someTypeInResourceAssembly, string manifestResourceName)
{
return new Uri("http://www.google.com");
}
}
and then register it in web.config:
<dotNetOpenAuth>
<webResourceUrlProvider type="AppName.CustomResourceProvider, AppName" />
...
</dotNetOpenAuth>
But I would recommend you using the openid-selector library for generating login forms.
I came across this problem when I was trying to get the NerdDinner OpenID working for MVC3/razor. The solution that has worked for me is:
Create this class in your solution: (this was found in one of the NerdDinner builds - http://nerddinner.codeplex.com/SourceControl/changeset/view/55257#1328982 (thanks to JasonHaley)
for some reason, this file isn't in the latest build for NerdDinner MVC3/Razor
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DotNetOpenAuth;
namespace <Your App>.Services
{
public class EmbeddedResourceUrlService : IEmbeddedResourceRetrieval
{
private static string pathFormat = "{0}/{1}/Resource/GetWebResourceUrl?assemblyName={2}&typeName={3}&resourceName={4}";
//private static string pathFormat = "{0}/Resource/GetWebResourceUrl";
public Uri GetWebResourceUrl(Type someTypeInResourceAssembly, string manifestResourceName)
{
if (manifestResourceName.Contains("http"))
{
return new Uri(manifestResourceName);
}
else
{
var assembly = someTypeInResourceAssembly.Assembly;
// HACK
string completeUrl = HttpContext.Current.Request.Url.ToString();
string host = completeUrl.Substring(0,
completeUrl.IndexOf(HttpContext.Current.Request.Url.AbsolutePath));
var path = string.Format(pathFormat,
host,
HttpContext.Current.Request.ApplicationPath.Substring(1),
HttpUtility.UrlEncode(assembly.FullName),
HttpUtility.UrlEncode(someTypeInResourceAssembly.ToString()),
HttpUtility.UrlEncode(manifestResourceName));
return new Uri(path);
}
}
}
}
Then in your web.config, add this line:
<webResourceUrlProvider type="<Your App>.Services.EmbeddedResourceUrlService, <Your App>" />
just put in the DotNetOpenAuth section
you will also need this route set up: ( Html.OpenIdSelectorScripts helper method throwing NullReferenceException )
routes.MapRoute(
"OpenIdDiscover",
"Auth/Discover"
);