webapi IPrincipal and authorize - asp.net-mvc-4

this is about security MVC4 RC and "Install-Package Microsoft.AspNet.WebApi".
I create a custom Identity : System.Security.Principal.IIdentity where i store some valuable string's and int's in the authentication cookie:
[Serializable]
public class SiteIdentity : IIdentity
{
public SiteIdentity(string name, string displayName, int userId, int siteId)
{
this.Name = name;
this.DisplayName = displayName;
this.UserId = userId;
this.SiteId = siteId;
}
public SiteIdentity(string name, UserInfo userInfo)
: this(name, userInfo.DisplayName, userInfo.UserId, userInfo.SiteId)
{
if (userInfo == null) throw new ArgumentNullException("userInfo");
this.AuthenticationType = userInfo.AutheticationType;
this.ClaimsIdentifier = userInfo.ClaimsIdentifier;
}
public SiteIdentity(FormsAuthenticationTicket ticket)
: this(ticket.Name, UserInfo.FromString(ticket.UserData))
{
if (ticket == null) throw new ArgumentNullException("ticket");
}
... not complete but i think you guess.
But first of all the structure of my webapi controller. I have created and extension controller, from where i extend all my webapi controllers:
public class _AuthorizedApiController : ApiController
{
protected readonly Site.Web.Domain.Services.IUserServices _userServices;
public _AuthorizedApiController(Site.Web.Domain.Services.IUserServices userServices)
{
if (userServices == null) throw new ArgumentNullException("userServices");
this._userServices = userServices;
}
protected int CurrentUserId
{
get { return this.User.SiteIdentity().UserId; }
}
private Site.Web.Domain.Models.User currentUser;
public Site.Web.Domain.Models.User CurrentUser
{
get
{
return this.currentUser ??
(this.currentUser = this._userServices.GetUserFromIdentity(this.User.SiteIdentity()));
}
}
protected int CurrentSiteId
{
get { return this.User.SiteIdentity().SiteId; }
}
}
so my webapi controller is:
public class ServicioController : _AuthorizedApiController
{
//http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api
//http://www.asp.net/web-api/overview/web-api-routing-and-actions/exception-handling
static readonly IServicioStatusRepository repositoryServicioStatus =
new ServicioStatusRepository(new Site.Web.Data.DatabaseFactory());
public ServicioController(Site.Web.Domain.Services.IUserServices userServices)
: base(userServices)
{
}
public IEnumerable<ServicioStatusA> GetServiciosStatus()
{
IEnumerable<ServicioStatusA> coleccion;
var estevalor = CurrentUser.SiteId;
}
As you can see i use IoC but the issue is that when i try to read CurrentUser.SiteId. I get this error:
Unable to cast object of type 'System.Web.Security.FormsIdentity' to type 'Site.Web.Models.SiteIdentity'.
in this return function:
public static Site.Web.Models.SiteIdentity SiteIdentity(this System.Security.Principal.IPrincipal principal)
{
return (Site.Web.Models.SiteIdentity)principal.Identity;
}
I use this "artifact" in global.asax.cs to keep session and information:
public override void Init()
{
this.PostAuthenticateRequest += this.PostAuthenticateRequestHandler;
// this.EndRequest += this.EndRequestHandler;
base.Init();
}
private void PostAuthenticateRequestHandler(object sender, EventArgs e)
{
if (IsWebApiRequest())
{
string esto = "popopopopo";
}
HttpCookie authCookie = this.Context.Request.Cookies[FormsAuthentication.FormsCookieName];
if (IsValidAuthCookie(authCookie))
{
// var formsAuthentication = ServiceLocator.Current.GetInstance<IFormsAuthentication>();
var formsAuthentication = new FormsAuthenticationService();
var ticket = formsAuthentication.Decrypt(authCookie.Value);
var siteIdentity = new SiteIdentity(ticket);
this.Context.User = new GenericPrincipal(siteIdentity, null);
// Reset cookie for a sliding expiration.
formsAuthentication.SetAuthCookie(this.Context, ticket);
}
}
and what i guess is that when there is a "normal" MVC call every works fine but when there is a webapi call i can recover everything from the cookie but i´ve got:
System.Security.Principal.GenericPrincipal
+ Identity: Site.Web.Model.SiteIdentity
instead of :
System.Security.Principal.GenericPrincipal
+ Identity: System.web.security.FormsIdentity
Thank you in advance for your support
ADEN-UM:
googling i try to keep the Identity in the thread also, so inside PostAuthenticateRequestHandler i type:
System.Threading.Thread.CurrentPrincipal = this.Context.User;
but now i have for all request the following error in any request not only webapi:
[SerializationException: Type is not resolved for member 'Site.Web.Models.SiteIdentity,Site.Web, Version=1.0.0.0, Culture=neutral,PublicKeyToken=null'.]
Microsoft.VisualStudio.WebHost.Connection.get_RemoteIP() +0
Microsoft.VisualStudio.WebHost.Request.GetRemoteAddress() +65
System.Web.HttpRequest.get_IsLocal() +23
System.Web.Configuration.CustomErrorsSection.CustomErrorsEnabled(HttpRequest request) +86
System.Web.HttpContextWrapper.get_IsCustomErrorEnabled() +45
System.Web.Mvc.HandleErrorAttribute.OnException(ExceptionContext filterContext) +72
System.Web.Mvc.ControllerActionInvoker.InvokeExceptionFilters(ControllerContext controllerContext, IList`1 filters, Exception exception) +115
System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult) +105
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +57
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +45
System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult) +14
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +25
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +61
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +25
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +49
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__4(IAsyncResult asyncResult) +28
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +25
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.<>c__DisplayClasse.<EndProcessRequest>b__d() +50
System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7
System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +60
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8970061
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184

Related

ASP .NET Core 2.0 deployment unable to connect with WCF service in production

I have a .NET core app in that has connected WCF Service, everything works fine in the dev environment, but in the deployment environment the service is not connecting.
I published the ASP .NET core project and hosted it in IIS, the published app also contains the ConnectedService.json file:
{
"ProviderId": "Microsoft.VisualStudio.ConnectedService.Wcf",
"Version": "15.0.20628.921",
"GettingStartedDocument": {
"Uri": "https://go.microsoft.com/fwlink/?linkid=858517"
},
"ExtendedData": {
"Uri": "http://localhost:8759/Design_Time_Addresses/CECWcfServiceLib/CECService/text/mex",
"Namespace": "CEC_WCF_Service",
"SelectedAccessLevelForGeneratedClass": "Public",
"GenerateMessageContract": false,
"ReuseTypesinReferencedAssemblies": true,
"ReuseTypesinAllReferencedAssemblies": true,
"CollectionTypeReference": {
"Item1": "System.Array",
"Item2": "System.Runtime.dll"
},
"DictionaryCollectionTypeReference": {
"Item1": "System.Collections.Generic.Dictionary`2",
"Item2": "System.Collections.dll"
},
"CheckedReferencedAssemblies": [],
"InstanceId": null,
"Name": "CEC_WCF_Service",
"Metadata": {}
}
}
The error I get is
System.NullReferenceException: Object reference not set to an instance of an object.
at AspNetCore.Views_Home_CEC_Dashboard.ExecuteAsync() in D:\Users\sajja\source\repos\CECDashboard\CECDashboard\Views\Home\CEC_Dashboard.cshtml:line 9
at Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageCoreAsync(IRazorPage page, ViewContext context)
at Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageAsync(IRazorPage page, ViewContext context, Boolean invokeViewStarts)
at Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderAsync(ViewContext context)
at Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ViewContext viewContext, String contentType, Nullable`1 statusCode)
at Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ActionContext actionContext, IView view, ViewDataDictionary viewData, ITempDataDictionary tempData, String contentType, Nullable`1 statusCode)
at Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor.ExecuteAsync(ActionContext context, ViewResult result)
at Microsoft.AspNetCore.Mvc.ViewResult.ExecuteResultAsync(ActionContext context)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeResultAsync(IActionResult result)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResultFilterAsync[TFilter,TFilterAsync]()
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResultExecutedContext context)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.ResultNext[TFilter,TFilterAsync](State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeResultFilters()
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResourceFilter()
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync()
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync()
at Microsoft.AspNetCore.Routing.EndpointMiddleware.Invoke(HttpContext httpContext)
at Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware.Invoke(HttpContext httpContext)
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
Am I missing a deployment configuration because this works fine in dev environment.
[Update] Code in the HomeController
public ActionResult CEC_Dashboard()
{
try
{
CEC_WCF_Service.CECServiceClient cECService = new CEC_WCF_Service.CECServiceClient();
var task1 = Task.Run(async () => await cECService.OpenAsync());
task1.Wait();
var task2 = Task.Run(async () => await cECService.GetAccountsAsync());
task2.Wait();
var accountsInfo = task2.Result.ToList();
var task3 = Task.Run(async () => await cECService.GetAccountStatsOnAccountAsync(1));
task3.Wait();
var account_Stats = task3.Result.ToList();
ViewData["Account_Stats"] = account_Stats;
ViewData["accountsInfo"] = accountsInfo;
ViewData["DefaultAccountsView"] = accountsInfo.Find(o => o.AccountId == 1);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return View();
}
So, after days of research I figured out the problem. As originally thought, the problem was indeed related to the WCF configuration for production deployment.
So, here is what I did after research on multiple threads.
1- Injected IConfiguration in HomeController
public class HomeController : Controller
{
private IConfiguration configuration;
public HomeController(IConfiguration iConfig)
{
configuration = iConfig;
}
<...More Class Code here ...>
}
2- Added the settings in appsettings.json
"MyService": {
"EndpointUrl": "http://localhost:8082/hello?wsdl"
}
3- Here is what was missing while doing production deployment. The Reference.cs file has the address of the dev time address, so I did all the above to mitigate and be able to load the production address at run time.
This method is referred in one of the post Reference Post
//
var EndPoint = configuration.GetSection("MyService").GetSection("EndpointUrl").Value;
System.ServiceModel.BasicHttpBinding result = new System.ServiceModel.BasicHttpBinding();
result.MaxBufferSize = int.MaxValue;
result.ReaderQuotas = System.Xml.XmlDictionaryReaderQuotas.Max;
result.MaxReceivedMessageSize = int.MaxValue;
result.AllowCookies = true;
//
CEC_WCF_Service.CECServiceClient cECService = new CEC_WCF_Service.CECServiceClient(result, new System.ServiceModel.EndpointAddress(EndPoint));
var task1 = Task.Run(async () => await cECService.OpenAsync());
task1.Wait();
This resolved the issue for production deployment!

System.Data.SqlClient.SqlException: Invalid column name 'Faculty_Id'

Controller:
public async Task<ActionResult> Create([Bind(Include = "Id,Terms,Semester,Sections,Course,CreditHourTheory,CreditHourLab,Labinstructor,Faculty,Rooms,Day,Date,TimeStart,TimeEnd")] TimeTable.Models.TimeTable timetable)
{
if (ModelState.IsValid)
{
db.TimeTable.Add(timetable);
await db.SaveChangesAsync();
return RedirectToAction("Create");
}
return View(timetable);
}
In the view i have use the dropdown to get the value from the database and to insert this selected value in the another table in database
#Html.DropDownList("FId", null, String.Empty, new { #class = "form-control input-md cc2", #disabled = "disabled", #required = "" })
Model:
[Table("TimeTable")]
public class TimeTable
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Terms { get; set; }
public string Semester { get; set; }
public int SectionsId { get; set; }
[ForeignKey("SectionsId")]
public Sections Sections { get; set; }
public int CourseId { get; set; }
[ForeignKey("CourseId")]
public Course Course { get; set; }
public string CreditHourTheory { get; set; }
public string CreditHourLab { get; set; }
public int? LabInstructorId { get; set; }
[ForeignKey("LabInstructorId")]
public Faculty Labinstructor { get; set; }
public int FacultyId { get; set; }
[ForeignKey("FacultyId")]
public Faculty Faculty { get; set; }
public int RoomId { get; set; }
[ForeignKey("RoomId")]
public Rooms Rooms { get; set; }
public string Day { get; set; }
public DateTime Date { get; set; }
public TimeSpan TimeStart { get; set; }
public TimeSpan TimeEnd { get; set; }
}
Server Error in '/' Application.
Invalid column name 'Faculty_Id'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.SqlClient.SqlException: Invalid column name 'Faculty_Id'.
Source Error:
Line 54: {
Line 55: db.TimeTable.Add(timetable);
Line 56: await db.SaveChangesAsync();
Line 57: return RedirectToAction("Create");
Line 58: }
Source File: c:\Users\NoorMuhammad\Documents\Visual Studio 2013\Projects\TimeTable\TimeTable\Controllers\HomeController.cs Line: 56
Stack Trace:
[SqlException (0x80131904): Invalid column name 'Faculty_Id'.]
System.Data.SqlClient.SqlCommand.b__24(Task1 result) +1792654
System.Threading.Tasks.ContinuationResultTaskFromResultTask2.InnerInvoke() +81
System.Threading.Tasks.Task.Execute() +45
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
System.Runtime.CompilerServices.TaskAwaiter1.GetResult() +24
System.Data.Entity.Utilities.CultureAwaiter1.GetResult() +123
System.Data.Entity.Core.Mapping.Update.Internal.d__0.MoveNext() +1068
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
System.Runtime.CompilerServices.TaskAwaiter1.GetResult() +24
System.Data.Entity.Utilities.CultureAwaiter1.GetResult() +71
System.Data.Entity.Core.Mapping.Update.Internal.d__0.MoveNext() +676
[UpdateException: An error occurred while updating the entries. See the inner exception for details.]
System.Data.Entity.Core.Mapping.Update.Internal.d__0.MoveNext() +1044
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
System.Runtime.CompilerServices.TaskAwaiter1.GetResult() +24
System.Data.Entity.Utilities.CultureAwaiter1.GetResult() +66
System.Data.Entity.Core.Objects.d__3d1.MoveNext() +1138
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
System.Runtime.CompilerServices.TaskAwaiter1.GetResult() +24
System.Data.Entity.Utilities.CultureAwaiter1.GetResult() +66
System.Data.Entity.Core.Objects.<SaveChangesToStoreAsync>d__39.MoveNext() +619
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
System.Runtime.CompilerServices.ConfiguredTaskAwaiter.GetResult() +24
System.Data.Entity.SqlServer.<ExecuteAsyncImplementation>d__91.MoveNext() +457
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
System.Runtime.CompilerServices.TaskAwaiter1.GetResult() +24
System.Data.Entity.Utilities.CultureAwaiter1.GetResult() +66
System.Data.Entity.Core.Objects.d__31.MoveNext() +1165
[DbUpdateException: An error occurred while updating the entries. See the inner exception for details.]
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
System.Runtime.CompilerServices.TaskAwaiter1.GetResult() +24
TimeTable.Controllers.<Create>d__8.MoveNext() in c:\Users\NoorMuhammad\Documents\Visual Studio 2013\Projects\TimeTable\TimeTable\Controllers\HomeController.cs:56
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
System.Runtime.CompilerServices.TaskAwaiter.GetResult() +21
System.Threading.Tasks.TaskHelpersExtensions.ThrowIfFaulted(Task task) +61
System.Web.Mvc.Async.TaskAsyncActionDescriptor.EndExecute(IAsyncResult asyncResult) +114
System.Web.Mvc.Async.<>c__DisplayClass37.<BeginInvokeAsynchronousActionMethod>b__36(IAsyncResult asyncResult) +66
System.Web.Mvc.Async.WrappedAsyncResult1.CallEndDelegate(IAsyncResult asyncResult) +47
System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +136
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +102
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +49
System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d() +117
System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +323
System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +323
System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +323
System.Web.Mvc.Async.<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32(IAsyncResult asyncResult) +44
System.Web.Mvc.Async.WrappedAsyncResult1.CallEndDelegate(IAsyncResult asyncResult) +47
System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +136
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +102
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +50
System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +72
System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +185
System.Web.Mvc.Async.WrappedAsyncResult1.CallEndDelegate(IAsyncResult asyncResult) +42
System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +133
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +40
System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +34
System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +70
System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +139
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +44
System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +39
System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +62
System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +139
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +39
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +39
System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +39
System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +70
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +40
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +38
System.Web.CallHandlerExecutionStep.OnAsyncHandlerCompletion(IAsyncResult ar) +129
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.34274

RavenDb JsonIgnore Attribute throws error when generating document key

Im moving out from Guid to string (HiLo) keys which is suggested by RavenDb docs.
Some of my DomainEvents gets fired inside the constructor so the Id should be known before firing the event. When I was using Guid, I'll just create Guid.NewGuid() to generate Id. But for the HiLo provided by RavenDb, what I did was an extension method to generate keys for me and then pass to my Entity constructor as argument.
RavenDb Version: RavenDb.Client 3.0.30000
Note that this is a copy-paste code I found on the internet :)
public static class RavenDbExtensions
{
public static string GenerateIdFor<T>(this IDocumentSession session)
{
// We need the advanced session in order to ensure that the keys are generated in the correct database.
// session.Advanced.DocumentStore.DatabaseCommands is not sufficient.
var advancedSession = session.Advanced as DocumentSession;
if (advancedSession == null)
throw new InvalidOperationException();
// An entity instance is required to generate a key, but we only have a type.
// In our case, the entities don't have public constructors so we must use reflection.
var entity = Activator.CreateInstance(typeof(T), true);
// Generate an ID using the commands and conventions from the current session
return advancedSession.Conventions.GenerateDocumentKey(
advancedSession.DocumentStore.Identifier,
advancedSession.DatabaseCommands,
entity);
}
}
My controller method.
[HttpPost]
[ValidateAntiForgeryToken]
[Route("add", Name = "courses.add")]
public ActionResult Add(AddViewModel model)
{
if (!ModelState.IsValid)
{
model.Categories = DocumentSession.Query<Category>().ToList();
return View(model);
}
string courseId = DocumentSession.GenerateIdFor<Course>();
var course = Course.Create(
courseId,
model.Title,
CourseCode.FromString(model.Code),
StandardDuration.Create(model.Days, model.HoursPerDay),
model.StandardPrice,
model.CategoryId);
DocumentSession.Store(course);
return RedirectToAction("Add");
}
I have this class with JsonIgnore (Raven.Imports.Newtonsoft.Json) attribute
public class StandardDuration : ValueObject
{
private StandardDuration(int days, int hoursPerDay)
{
Days = days;
HoursPerDay = hoursPerDay;
}
public int Days { get; private set; }
public int HoursPerDay { get; private set; }
public static StandardDuration Create(int days, int hoursPerDay)
{
if (days <= 0)
throw new DomainModelException("Days should be atleast one");
if (hoursPerDay <= 0)
throw new DomainModelException("CreditHours should be greater than zero");
return new StandardDuration(days, hoursPerDay);
}
[JsonIgnore]
public int CreditHours
{
get { return HoursPerDay * Days; }
}
protected override IEnumerable<object> GetEqualityComponents()
{
yield return Days;
yield return HoursPerDay;
}
}
which throws an error
Attempt by method 'Raven.Client.Document.DocumentConvention.DefaultTypeTagName(System.Type)' to access method 'Raven.Imports.Newtonsoft.Json.Utilities.TypeExtensions.IsGenericType(System.Type)' failed.
UPDATE
I cant reproduce the error on the code above due to same issue but before showing the page.
But Im facing the same issue even on non JsonIgnore decorated classes.
public class Category : Entity
{
private Category() { }
private Category(Guid id, string name)
{
Id = id;
Name = name;
}
public string Name { get; private set; }
public static Category Create(Guid id, string name)
{
if (string.IsNullOrWhiteSpace(name))
throw new DomainModelException("Category name should not be blank or null.");
return new Category(id, name);
}
}
controller action
[HttpPost]
[Route("add", Name = "course_categories.add")]
public ActionResult Add(string name)
{
if (ModelState.IsValid)
{
var courseCategory = Category.Create(Guid.NewGuid(), name);
DocumentSession.Store(courseCategory);
AddSuccessMessage("Course Category created");
return RedirectToRoute("course_categories.add_page");
}
ModelState.AddModelError("", "An error occurred please try again.");
return View();
}
stack trace:
[MethodAccessException: Attempt by method 'Raven.Client.Document.DocumentConvention.DefaultTypeTagName(System.Type)' to access method 'Raven.Imports.Newtonsoft.Json.Utilities.TypeExtensions.IsGenericType(System.Type)' failed.]
Raven.Client.Document.DocumentConvention.DefaultTypeTagName(Type t) in c:\Builds\RavenDB-Stable-3.0\Raven.Client.Lightweight\Document\DocumentConvention.cs:264
Raven.Client.Document.DocumentConvention.GetTypeTagName(Type type) in c:\Builds\RavenDB-Stable-3.0\Raven.Client.Lightweight\Document\DocumentConvention.cs:296
Raven.Client.Document.DocumentConvention.DefaultFindFullDocumentKeyFromNonStringIdentifier(Object id, Type type, Boolean allowNull) in c:\Builds\RavenDB-Stable-3.0\Raven.Client.Lightweight\Document\DocumentConvention.cs:152
Raven.Client.Document.GenerateEntityIdOnTheClient.GetIdAsString(Object entity, Object value, String& id) in c:\Builds\RavenDB-Stable-3.0\Raven.Client.Lightweight\Document\GenerateEntityIdOnTheClient.cs:49
Raven.Client.Document.GenerateEntityIdOnTheClient.TryGetIdFromInstance(Object entity, String& id) in c:\Builds\RavenDB-Stable-3.0\Raven.Client.Lightweight\Document\GenerateEntityIdOnTheClient.cs:33
Raven.Client.Document.InMemoryDocumentSessionOperations.Store(Object entity) in c:\Builds\RavenDB-Stable-3.0\Raven.Client.Lightweight\Document\InMemoryDocumentSessionOperations.cs:646
Web.Features.CourseCategories.CourseCategoriesController.Add(String name) in E:\Projects\Akademia\Presentation\Web\Features\CourseCategories\CourseCategoriesController.cs:39
lambda_method(Closure , ControllerBase , Object[] ) +104
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +157
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27
System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +22
System.Web.Mvc.Async.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +32
System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d() +50
System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +225
System.Web.Mvc.Async.<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +34
System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +26
System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +100
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27
System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +13
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +36
System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +12
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +22
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +26
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +21
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +28
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9721605
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

System.NotImplementedException : "The method or operation is not implemented." FoolProofValidation

In my MVC4 application I'm using MVC FoolProof library
In my Metadata class I have
public class R_DealsMetaData
{
public int ID { get; set; }
public int UserId { get; set; }
public bool CodeGenerated { get; set; }
[Required(ErrorMessage="Please Enter Description")]
[Display(Name="Promotion Name:")]
public string Description { get; set; }
[Required(ErrorMessage = "Please select one Option")]
[Display(Name = "Deal Buy:")]
public int Buy { get; set; }
[Required(ErrorMessage = "Please select one Option")]
[Display(Name = "Deal Free:")]
public int Free { get; set; }
public Nullable<bool> Status { get; set; }
public string Type { get; set; }
[DataType(DataType.Date)]
public System.DateTime CreateDate { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
[Required(ErrorMessage = "Please select Expiry Date")]
[Display(Name = "Promotion Expiry Date:")]
public System.DateTime ExpiryDate { get; set; }
[RequiredIf("Type", "P", ErrorMessage = "Please select")]
public Nullable<int> PointEarnType { get; set; }
[RequiredIf("PointEarnType", 2, ErrorMessage = "Please enter value")]
public string PointEarnMealText { get; set; }
[RequiredIf("Type","V",ErrorMessage="Please enter")]
public string VolumeBuyText { get; set; }
[RequiredIf("Type","V",ErrorMessage="Please enter")]
public string VolumeEarnText { get; set; }
}
But at my controller post method an exception has been thrown on db.SaveChanges
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(R_Deals r_deals)
{
if (ModelState.IsValid)
{
db.R_Deals.Add(r_deals);
db.SaveChanges();
}
}
Following are the details of exception
An unexpected exception was thrown during validation of 'PointEarnType' when invoking Foolproof.RequiredIfAttribute.IsValid. See the inner exception for details.
Stack Trace Details
[NotImplementedException: The method or operation is not implemented.]
Foolproof.ModelAwareValidationAttribute.IsValid(Object value) +59
System.ComponentModel.DataAnnotations.ValidationAttribute.IsValid(Object value, ValidationContext validationContext) +115
System.ComponentModel.DataAnnotations.ValidationAttribute.GetValidationResult(Object value, ValidationContext validationContext) +29
System.Data.Entity.Internal.Validation.ValidationAttributeValidator.Validate(EntityValidationContext entityValidationContext, InternalMemberEntry property) +198
[DbUnexpectedValidationException: An unexpected exception was thrown during validation of 'PointEarnType' when invoking Foolproof.RequiredIfAttribute.IsValid. See the inner exception for details.]
System.Data.Entity.Internal.Validation.ValidationAttributeValidator.Validate(EntityValidationContext entityValidationContext, InternalMemberEntry property) +299
System.Data.Entity.Internal.Validation.PropertyValidator.Validate(EntityValidationContext entityValidationContext, InternalMemberEntry property) +148
System.Data.Entity.Internal.Validation.EntityValidator.ValidateProperties(EntityValidationContext entityValidationContext, InternalPropertyEntry parentProperty, List`1 validationErrors) +203
System.Data.Entity.Internal.Validation.TypeValidator.Validate(EntityValidationContext entityValidationContext, InternalPropertyEntry property) +105
System.Data.Entity.Internal.Validation.EntityValidator.Validate(EntityValidationContext entityValidationContext) +55
System.Data.Entity.Internal.InternalEntityEntry.GetValidationResult(IDictionary`2 items) +299
System.Data.Entity.DbContext.ValidateEntity(DbEntityEntry entityEntry, IDictionary`2 items) +89
System.Data.Entity.DbContext.GetValidationErrors() +289
System.Data.Entity.Internal.InternalContext.SaveChanges() +107
System.Data.Entity.Internal.LazyInternalContext.SaveChanges() +53
System.Data.Entity.DbContext.SaveChanges() +52
MOU.Controllers.RDealsController.Create(R_Deals r_deals) in e:\MVC Projects\MouMvc\Controllers\RDealsController.cs:197
lambda_method(Closure , ControllerBase , Object[] ) +180
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +59
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +434
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +60
System.Web.Mvc.Async.AsyncControllerActionInvoker.InvokeSynchronousActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +50
System.Web.Mvc.Async.<>c__DisplayClass42.<BeginInvokeSynchronousActionMethod>b__41() +75
System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +44
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +139
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +102
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +49
System.Web.Mvc.Async.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33() +125
System.Web.Mvc.Async.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49() +321
System.Web.Mvc.Async.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49() +321
System.Web.Mvc.Async.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49() +321
System.Web.Mvc.Async.<>c__DisplayClass37.<BeginInvokeActionMethodWithFilters>b__36(IAsyncResult asyncResult) +44
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +139
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +102
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +50
System.Web.Mvc.Async.<>c__DisplayClass2a.<BeginInvokeAction>b__20() +68
System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult) +184
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +136
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +40
System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult) +40
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +47
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +151
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +44
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +47
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +151
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +39
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +39
System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult asyncResult) +45
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +47
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +151
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +40
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +38
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9690164
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
What should I do in this case? Not getting actually where I am going wrong .
Please Help me! Thanks
Foolproof Validation has problems with EntityFramework.
For more details see this bug report

Authorize attribute not working with Windows Authentication application

I have an MVC4 application whereby I have assigned roles to my user using a custom role provider so that when I check User.IsInRole against my User table it determines which links etc to display on screen in my _Layout.cshtml page. This is working on the Layout page in that the correct links are appearing.
However when I secure my Admin controller using the
[Authorize(Roles = "Admin")]
I am getting the following stack trace from an object not set to instance of an object error:
[NullReferenceException: Object reference not set to an instance of an object.]
System.Web.Mvc.AuthorizeAttribute.AuthorizeCore(HttpContextBase httpContext) +39
System.Web.Mvc.AuthorizeAttribute.OnAuthorization(AuthorizationContext filterContext) +159
System.Web.Mvc.ControllerActionInvoker.InvokeAuthorizationFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor) +96
System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__1e(AsyncCallback asyncCallback, Object asyncState) +446
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext, String actionName, AsyncCallback callback, Object state) +302
System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__17(AsyncCallback asyncCallback, Object asyncState) +30
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state) +382
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +317
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +15
System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__2(AsyncCallback asyncCallback, Object asyncState) +71
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +249
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +50
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +301
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
What exactly is in this Filter context? This works without any further configuration when I use ADFS or Forms based authentication but when using Windows based authentication I have had to do the following to get IsInRole method working:
this.UserName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
if (this.UserName.Contains("\\"))
{
string[] stringArray = this.UserName.Split(new Char[] { '\\' });
this.UserName = stringArray[1];
MyUser identity = userRepository.Get(u => u.Username == this.UserName).FirstOrDefault();
HttpContext.Current.User = identity;
}
Do I need to configure some other HttpContext proper in order for Authorize attribute to work in same manner as IsInRole method?
In the forms case, it could be anything but it is very common to implement a username password form with a lookup by username in a user table, based on the code presented it looks like the repository expects just a username, it just turns out that windows.identity.name returns domain\user. That's where the extra effort comes in to split into domain, user. example below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcApplication6
{
public class DemoAuthAttribute : AuthorizeAttribute
{
// create a file like auth.cs in the mvc project
// called
// [DemoAuth("BAR")]
// as an attibute on a controller method
private string _role;
public DemoAuthAttribute(string role)
{
_role = role; // should be exapanded to handle more than one
}
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
return httpContext.Request.IsAuthenticated && _role == "FOO";
// lookup the current user in database does the user have role as specificed by the attribute?
// if yes sucess if not fail.
}
public override void OnAuthorization(AuthorizationContext filterContext)
{
if (filterContext == null)
{
throw new ArgumentNullException("filterContext");
}
if (AuthorizeCore(filterContext.HttpContext))
{
// your custom logic here
string text = string.Format("<u><h5>Auth successfull.....</h5></u></br>");
filterContext.HttpContext.Response.Write(text);
}
else
{
// RedirectResult, etc.
string text = string.Format("<u><h5>Auth unsuccessfull.....</h5></u></br>");
filterContext.HttpContext.Response.Write(text);
}
}
}
}