I have taken code from this page. Basically, i am trying to require SSL on all requests. Here is the code I have:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.Web.Mvc;
using System.Net.Http;
using System.Web.Http.Controllers;
namespace Test
{
public class RequireSSL : ActionFilterAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
if (actionContext.Request.RequestUri.Scheme != Uri.UriSchemeHttps)
{
actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden)
{
ReasonPhrase = "HTTPS Required"
};
}
else
{
base.OnAuthorization(actionContext);
}
}
}
}
The problem I am facing is I have a blue scriggily line under OnAuthorization that says "No suitable method to override". Not sure how to fix this. Any ideas?
There is an attribute RequireHttpsAttrobute you can use: RequireHttpsAttribute
If you look carefully at the example, it's deriving from AuthorizationFilterAttribute, not ActionFilterAttribute. If you change that in your example, then it compiles correctly.
Related
I am using Entity Framework Core. I want to create an async method which will create new user in my database, i have included all the libraries I need, but some methods that are supposed to work with database are missing, I have almost every async method but i am missing AddAsync and RemoveAsync. When I type AddAsync manually I get the following error message: "Error CS1061 'DbSet' does not contain a definition for 'AddAsync' and no accessible extension method 'AddAsync' accepting a first argument of type 'DbSet' could be found (are you missing a using directive or an assembly reference?)"
The class where the method is created has following code and libraries included:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity;
using System.Data;
using Microsoft.EntityFrameworkCore;
namespace ClassLibrary
{
public class Class1 : Interface1
{
public async Task AddKorisnik(Korisnici k)
{
using (ExtentEntities context = new ExtentEntities())
{
context.Korisnici.AddAsync();
await context.SaveChangesAsync();
}
}
}
}
The class where the DbContext is used is following:
namespace ClassLibrary
{
using System;
using System.Linq;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
public partial class ExtentEntities : DbContext
{
public ExtentEntities()
: base("name=ExtentEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<Korisnici> Korisnici { get; set; }
}
}
There is nothing asynchronous with adding an object to an in-memory DbSet<T>. You should use the synchronous Add method to do this.
SaveChangesAsync() is the method that actually connects asynchronously to the underlying database.
I'm building an OData 3 service on Web API 2.2.
The service is correctly returning the metadata for my entities, but returns 406 Not Available when I query one of the actual entities. I've done quite a bit of research (I'm currently following several tutorials), but I haven't found anything that actually works.
Here's my WebApiConfig:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Web.OData.Builder;
using System.Web.OData.Extensions;
namespace MyProject
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
ODataModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<MarvelCharacter>("MarvelCharacters");
config.MapODataServiceRoute(
routeName: "Marvel",
routePrefix: "dude",
model: builder.GetEdmModel());
}
}
}
And my controller (not complete, but you get the idea):
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.OData;
using System.Web.Http.OData.Query;
using Microsoft.Data.OData;
using MyProject;
namespace MyProject.Controllers
{
public class MarvelCharactersController : ODataController
{
private static ODataValidationSettings _validationSettings = new ODataValidationSettings();
// GET: odata/MarvelCharacters
public IHttpActionResult GetMarvelCharacters(ODataQueryOptions<MarvelCharacter> queryOptions)
{
// validate the query.
try
{
queryOptions.Validate(_validationSettings);
}
catch (ODataException ex)
{
return BadRequest(ex.Message);
}
var entities = new myEntities();
var marvelCharacters = (from c in entities.MarvelCharacters select c).ToList();
return Ok<IEnumerable<MarvelCharacter>>(marvelCharacters);
}
}
}
Turns out the answer to this one was pretty simple, but not covered well by any documentation I could find.
I was trying to implement an OData 3 endpoint on WebAPI 2.2. I was following several different tutorials, some for OData 3 and some for OData 4.
I was using OData 4 (System.Web.OData) in my WebApiConfig and OData 3 (System.Web.Http.OData) in my controller. Turns out, they don't play well together.
I decided to post the answer here in case anyone else has a similar issue.
To add a little value, and since I was mixing both anyway, I decided to go ahead and setup support for both version 3 and 4 by aliasing the namespaces in my WebApiConfig and then creating versioned controllers.
WebApiConfig:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using ODataV3 = System.Web.Http.OData;
using ODataV4 = System.Web.OData;
namespace MyProject
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// OData V3 Route
ODataV3.Builder.ODataModelBuilder builder3 = new ODataV3.Builder.ODataConventionModelBuilder();
builder3.EntitySet<MarvelCharacter>("MarvelCharactersV3");
// The MapODataRoute function is deprecated in WebAPI 2.2,
// but I haven't found an alternative for supporting OData 3.
config.Routes.MapODataRoute(
routeName: "Marvel3",
routePrefix: "dude3",
model: builder3.GetEdmModel());
// ODate V4 Route
ODataV4.Builder.ODataModelBuilder builder4 = new ODataV4.Builder.ODataConventionModelBuilder();
builder4.EntitySet<MarvelCharacter>("MarvelCharactersV4");
ODataV4.Extensions.HttpConfigurationExtensions.MapODataServiceRoute(
configuration: config,
routeName: "Marvel4",
routePrefix: "dude4",
model: builder4.GetEdmModel());
}
}
}
MarvelCharactersV3 (OData 3):
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.OData; // OData V3
using System.Web.Http.OData.Query;
using Microsoft.Data.OData;
using MyProject;
namespace MyProject.Controllers
{
public class MarvelCharactersV3Controller : ODataController
{
private static ODataValidationSettings _validationSettings = new ODataValidationSettings();
// GET: odata/MarvelCharacters
public IHttpActionResult GetMarvelCharactersV3(ODataQueryOptions<MarvelCharacter> queryOptions)
{
// validate the query.
try
{
queryOptions.Validate(_validationSettings);
}
catch (ODataException ex)
{
return BadRequest(ex.Message);
}
var entities = new myEntities();
var marvelCharacters = (from c in entities.MarvelCharacters select c).ToList();
return Ok<IEnumerable<MarvelCharacter>>(marvelCharacters);
}
}
}
MarvelCharactersV4 (OData 4):
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.OData; // OData 4
using System.Web.OData.Query;
using Microsoft.Data.OData;
using MyProject;
namespace MyProject.Controllers
{
public class MarvelCharactersV4Controller : ODataController
{
private static ODataValidationSettings _validationSettings = new ODataValidationSettings();
// GET: odata/MarvelCharacters
public IHttpActionResult GetMarvelCharactersV4(ODataQueryOptions<MarvelCharacter> queryOptions)
{
// validate the query.
try
{
queryOptions.Validate(_validationSettings);
}
catch (ODataException ex)
{
return BadRequest(ex.Message);
}
var entities = new myEntities();
var marvelCharacters = (from c in entities.MarvelCharacters select c).ToList();
return Ok<IEnumerable<MarvelCharacter>>(marvelCharacters);
}
}
}
It's probably not the best architecture (I will probably create a library to consolidate similar code between the controllers), but I've tested and I can successfully query via OData 3 and OData 4, so I'm happy enough with it for now.
.......So, I have the below class which I have created as part of my automated test pack, but I am getting an error against the 'ListPostsPage.GoTo(PostType.Page)' line of code, advising that: 'the name PostType does not exist in the current context'. The code for this class is below:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WordpressTests
{
[TestClass]
public class PageTests
{
[TestInitialize]
public void Init()
{
Driver.Initialise();
}
[TestMethod]
public void CanEditAPage()
{
LoginPage.GoTo();
LoginPage.LoginAs("XXXXXX").WithPassword("XXXXXX").Login();
**ListPostsPage.GoTo(PostType.Page);**
ListPostsPage.SelectPost("Sample Page");
Assert.IsTrue(NewPostPage.IsInEditMode(), "Wasn't in edit mode");
Assert.AreEqual("Sample Page", NewPostPage.Title, "Title did not match");
}
[TestCleanup]
public void Cleanup()
{
Driver.Close();
}
}
}
Just for reference, the code for the ListPostsPage class is as follows:
using OpenQA.Selenium;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WordpressTests
{
public class ListPostsPage
{
public static void GoTo(PostType postType)
{
switch (postType)
{
case PostType.Page:
Driver.Instance.FindElement(By.Id("menu-pages")).Click();
Driver.Instance.FindElement(By.LinkText("All Pages")).Click();
break;
}
}
public static void SelectPost(string title)
{
var postLink = Driver.Instance.FindElement(By.LinkText("Sample Page"));
postLink.Click();
}
public enum PostType
{
Page
}
}
}
Does anyone have any ideas as to what the issue may be? Please bear in mind I am fairly new to this, so please be nice! :-)
Any help would be much appreciated.
Cheers
Andy
PostType is an enum member of ListPostsPage but you're trying to access it as if it were a static class.
You should do this:
ListPostsPage.GoTo(ListPostsPage.PostType.Page);
A bit rusty here with regards to WCF Services.
I have a custom class named cSecurity.cs which does some custom functions.
I want to use this custom class inside my Service:
This is the App.svc.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
namespace AppServices
{
public class App : IApp
{
public cSecurity _csec;
public string GetItems(int agentID, string agentName)
{
// Need to use some functions from the cSecurity class here???
return _csec.getItems();
}
}
}
This is the cSecurity.cs class:
using System.Collections;
using System.Configuration;
using System.Net;
namespace AppServices
{
public class cSecurity
{
// Some functions defined here....
public string getItems(){
return string.Empty;
}
}
}
But I am getting an error on the line:
public cSecurity _csec;
"The type or namespace name 'cSecurity' could not be found."
This seems pretty trivial but I seem to be lost here.
Appreciate any insight. Thanks.
For some reason, the solution for this was for me to close and restart VS. Not sure what caused the class for it to be not referenced by VS.
I am not sure what do I am missing but I really cannot refer to
User.Identity under OnActionExecuting(ActionExecutingContext filterContext)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using System.Web.Routing;
.....
public class RealUserAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
/// if (User.Identity.IsAuthenticated)
Any clue how to fix it?
I found the solution.
It should be
filterContext.HttpContext.User.Identity.IsAuthenticated
I believe that you should be using AuthorizeAtribute instead of ActionFilter. Try something like this:
using System.Web;
using System.Web.Mvc;
public class AuthorizeUser : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
var id = filterContext.RequestContext.HttpContext.User.Identity;
}
}
filterContext.RequestContext.HttpContext.Request.IsAuthenticated
works! and no need to check id User or User.Identity are null