Menu
  • HOME
  • TAGS

Sessions can't store serialized objects?

asp.net-mvc-6

OK, looks like you have to manually serialize the object to a byte array with the BinaryFormatter and then add it, to deserialize it is the same but in reverse, get the byte array an deserialized to the object, also with a BynaryFormatter.

How to get Microsoft.AspNet.Http.HttpContext instance in Class Constructor using DI

c#,asp.net-mvc,dependency-injection,asp.net-5,asp.net-mvc-6

Inject IHttpContextAccessor in the constructor

Increasing max. request length in asp.net 5 (vNext)

asp.net,iis,iis-express,asp.net-5,asp.net-mvc-6

If you are dealing with IIS then you still need web.config file to configure httpruntime. You can add web.config to your solution. For that click on wwwroot folder and add web.config file over there. After that you can provide your setting over there and it works with IIS just like...

Problems publishing asp vnext website on IIS 8

iis,asp.net-5,visual-studio-2015,asp.net-mvc-6

ASP 4.5 wasn't installed , even though i had ASP.NET options in IIS Control panel . In order to install it you have to go to Add Roles and Features Web Server IIS / Web Server / Application Development and check ASP .NET 4.5 and .NET Extensibility 4.5 (i'm not...

How and Where to tell if a ViewComponent has been invoked x times in a view?

asp.net-mvc-6

You can use HttpContext.Items which has the advantage of not using the session. These items are stored and shared per request, which would also fit your objective. In your viewComponent you can add/retrieve an item as in this.Context.Items["MyComponentInvocationCount"]. Whenever the count is greater than 2 you can just return an...

How to use soap web services in MVC 6 using asp.net 5?

asp.net-5,asp.net-mvc-6

I have answered few days back on following question. ASP.NET 5 add WCF service reference In above case there is a WCF service and in your case it is Web Service. Following thing you should concern or consider. It will not work with CoreCLR You have to add reference to...

How to Edit and Continue in ASP.Net MVC 6

c#,asp.net-5,visual-studio-2015,asp.net-mvc-6

Edit and Continue does not work for ASP.NET 5 applications at this point in Visual Studio 2015, but it is planned to support it in the final 2015 release. For more information about VS2015 ENC changes, have a look at this blog entry: http://blogs.msdn.com/b/visualstudioalm/archive/2015/04/29/net-enc-support-for-lambdas-and-other-improvements-in-visual-studio-2015.aspx...

Unable to use my HtmlHelper in views

c#,asp.net-5,asp.net-mvc-6

Apparently in MVC6 the first argument has to be IHtmlHelper instead of HtmlHelper Here is the modified code : public static HtmlString YokoTextBoxFor<TModel, TProperty>(this IHtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, string identifiant, string label) { string htmlString = string.Format("<span class=\"input\">" + "{0}" + "<label class=\"input-label label-yoko\" for=\"{1}\">" + "<span class=\"label-content label-content-yoko\">{2}</span>"...

Can't send parameters through POST on asp.net vNext app. (beta 3) (MV6, mono, EF7, OSX)

asp.net,osx,post,mono,asp.net-mvc-6

I don't really know with mvc6 but with mvc5 a simple string parameter was sent in the query string. Did you tried to remove the [FromBody] EDIT: In MVC5 a simple string parameter can be sent through a form post, a query string or a route value....

WS-Federation sign-in Asp.NET 5 MVC 6 ADFS

asp.net,asp.net-5,adfs,asp.net-mvc-6,ws-federation

As you already figured out, the WS-Federation middleware has not been ported to ASP.NET 5 yet, but don't panic, it will definitely be: https://twitter.com/blowdart/status/610526268908535808 In the meantime, you can use the OWIN/Katana 3 WS-Federation middleware in an ASP.NET 5 application with a tiny IAppBuilder/IApplicationBuilder adapter (like this one: https://github.com/aspnet-contrib/AspNet.Security.OpenIdConnect.Server/blob/vNext/samples/Mvc/Mvc.Server/Extensions/AppBuilderExtensions.cs#L50), but...

Rendering Views from external assemblies in MVC6

c#,asp.net-mvc-6

I ended up solving this in, what I believe to be, an incredibly hacky way. Since the views are in each project, inside the src folder, I changed the RazorViewEngine root from the Mvc application, in the src\Branch.Web, to just src. So every view has to be preffixed with the...

Deploy MVC 6 app in IIS

asp.net-5,visual-studio-2015,asp.net-mvc-6

File System publish is actually exactly what you want; All DNX applications are stand-alone, whether for ASP.NET 5 or a console app. When you publish to the File System, you get a few folders; the wwwroot (assuming you kept the default in your project.json) folder is where IIS should point....

ASP.NET MVC 6 (vNext) not properly linking to files

asp.net,asp.net-mvc,asp.net-mvc-6

Removing app.UseWelcomePage(); from Startup.cs fixed this, as per Sami Kuhmonen's suggestion (and helpful link to https://github.com/aspnet/Home/issues/113)

OAuth Authorization Service in ASP.Net MVC 6

asp.net,oauth,asp.net-5,asp.net-mvc-6

Don't waste your time looking for an OAuthAuthorizationServerMiddleware alternative in ASP.NET 5, the ASP.NET team simply decided not to port it: https://github.com/aspnet/Security/issues/83 I suggest having a look to AspNet.Security.OpenIdConnect.Server, an experimental fork of the OAuth2 authorization server middleware that comes with Katana 3: there's an OWIN/Katana 3 version, and an...

Add namespace to all views in ASP.NET MVC 6

asp.net-5,asp.net-mvc-6

For <= beta3 bits (what you're most likely using) you should add an @using statements to your _ViewStart.cshtml. Aka: _ViewStart.cshtml: @using MyProject.WebUI.Helpers If you don't have a _ViewStart.cshtml you can create one and just make sure it's in the same path or parent path of the view you want it...

asp.net 5: Bind attribute with Include parameter - include is not a valid named attribute argument

attributes,model-binding,asp.net-5,asp.net-mvc-6

In MVC 6, the Include property no longer has a setter. You need to pass the list of bound properties using the constructor: public BindAttribute(params string[] include) { Include = include; } And in your case: public IActionResult Create([Bind("Imie","Nazwisko","Wiek")] Pracownik pracownik) ...

EF7: Foreign Keys are not generated when adding to Database Context

c#,linq,asp.net-mvc-6,entity-framework-7

While it is a bit annoying, having to do that, for now I was able to solve the problem by renaming Permissions.PermissionId to Permissions.Id. Not a great solution and I have no clue why this affects anything (I added PermissionId as a key via Fluent API before), but it's working.

How to register custom UserStore & UserManager in DI

asp.net-5,asp.net-mvc-6,asp.net-identity-3

DI in general is intended for interface-driven development; .AddUserManager<ApplicationUserManager>() specifies an implementation UserManager<>, not the service interface. That means that it's still expecting you to get UserManager<ApplicationUser> and only use it that way; it'll give you an ApplicationUserManager. I'm assuming that you have additional methods you want to use on...

Web api with mvc 6 get element based on string

c#,asp.net-mvc,asp.net-web-api,asp.net-5,asp.net-mvc-6

Just remove :string. You're not really constraining the value of the id anyway - it's already a string in the URL. This fairly old blog post lists the available constraints - and you can see there's no :string constraint, because you don't need there to be. The constraints are used...

How do you change the default environment value in ASP.NET 5 that is available via IHostingEnvironment?

asp.net-5,asp.net-mvc-6

It should pick it up. 99.9% of me believes that you need to make sure your refresh the environment variables cache (e.g. VS needs restart if you changed the environment variable after you started the VS).

Use Office Interop on ASP.net MVC6 website

com,ms-word,office-interop,asp.net-mvc-6

Microsoft does not currently recommend, and does not support, Automation of Microsoft Office applications from any unattended, non-interactive client application or component (including ASP, ASP.NET, DCOM, and NT Services), because Office may exhibit unstable behavior and/or deadlock when Office is run in this environment. If you are building a solution...

VS2013 Is Not Compatible With VS2015 Project Type

asp.net-mvc,visual-studio-2013,asp.net-mvc-6

This repo is a fork of next version of ASP.NET MVC. It's built to run on VS 2015, C#6 and the next runtime. Even if you could open it, you couldn't compile or run it. Visual Studio 2015 can create both vNext (5) and ASP.NET 4.5/4.6 projects. ASP.NET 5 projects...

Running a Script on Build (e.g. Gulp or Grunt)

asp.net-mvc-6

You can use the "Task Runner Explorer" to automate this. (Use the Quick Launch in the upper right, Ctrl+Alt+\, or View->Other Windows->Task Runner Explorer.) Find the task you want to add ("bower" or "prepare", depending on the route you want to go), right click, and use the context menu to...

Access to Configuration object from Startup

c#,asp.net-mvc-6

An example of how you can do this: Let's assume you have a config.json like below: { "SomeSetting1": "some value here", "SomeSetting2": "some value here", "SomeSetting3": "some value here", "ActiveDirectory": { "DomainName": "DOMAIN-NAME-HERE" } } Create a POCO type having your option information: public class ActiveDirectoryOptions { public string DomainName...

Accessing dependency injected services in MVC 6

configuration,asp.net-5,asp.net-mvc-6

In general where ever you have access to HttpContext, you can use the property called RequestServices to get access to the services in DI. For example, to get access to the ILogger service from within ObjectResult. public override async Task ExecuteResultAsync(ActionContext context) { var logger = context.HttpContext.RequestServices.GetRequiredService<ILogger<ObjectResult>>(); The above usage...

MVC One controller many Index view

asp.net-mvc,asp.net-mvc-6

First of all you must enable attribute routing if you want multiple Index actions inside 1 controller. To enable this add the following to the RouteConfig.cs routes.MapMvcAttributeRoutes(); After this rename the MyReviews\Index.cshtml to MyReviewsIndex.cshtml inside the Account folder (Delete the MyReviews folder). So it looks like the following > Controllers...

@helper directive no longer works out of the box in ASP.NET5 MVC6 beta4.

razor,asp.net-5,asp.net-mvc-6

The @helper directive was removed since beta 4 because it imposed too many restrictions on other Razor features: https://github.com/aspnet/Razor/issues/281.

Kestrel on AspNet vNext doesnt serve index page under /

asp.net-mvc,osx,asp.net-5,asp.net-mvc-6,kestrel

You need to enable the DefaultFilesMiddleware using UseDefaultFiles() and place it before the call to UseStaticFiles(): app.UseDefaultFiles(); app.UseStaticFiles(); If you don't specify otherwise, the middleware uses the DefaultFilesOptions by default, which means this list of default file names will be used: default.htm default.html index.htm index.html See MSDN...

Visual Studio and KVM version mismatch

visual-studio,kvm,asp.net-mvc-6,kruntime

This is a limitation of the VS 2015 CTP <= 5. If you install the latest VS 2015 CTP 6, you should see that VS and KVM look in the same place for KRE's: ...

ActionLink (LinkText,Action,ControlName,AreaName,RoutesValue,html attribute)

asp.net,asp.net-mvc,routes,actionlink,asp.net-mvc-6

Specify your area name in the Route Values parameter: @Html.ActionLink("Go to contact page", "Index", "Drugs", new { area = "Growths", id = item.GroupMeasure_ID }, null)) ...

Getting the host name from a scoped service factory

dependency-injection,asp.net-5,asp.net-mvc-6

Since you're correctly defining it as scoped already, you can use the IHttpContextAccessor directly in your constructor of Foo: public class Foo { public Foo(IHttpContextAccessor contextAccessor) { var host = contextAccessor.HttpContext.Request.Host.Value; // remainder of constructor logic here } } Something similar is done many places in the GitHub repositories; it...

Publish to Azure fails with “ Unrecognized link extension 'contentLibExtension'” Error

azure,webdeploy,asp.net-mvc-6,vs-2015-preview

I had the same error. In my case the problem was an old version of "msdeploy.exe". After some searching I found one "msdeploy.exe" in the folder "C:\Program Files (x86)\IIS\Microsoft Web Deploy\msdeploy.exe" which caused the problem and another one in the folder "C:\Program Files (x86)\IIS\Microsoft Web Deploy V3\msdeploy.exe". As I don't...

Global Error Logging in ASP.Net MVC 6

asp.net,asp.net-web-api,asp.net-mvc-6

You question has 2 parts. 1) DI injectable filters 2) Global error handling. Regarding #1: You can use ServiceFilterAttribute for this purpose. Example: //Modify your filter to be like this to get the logger factory DI injectable. public class AppExceptionFilterAttribute : ExceptionFilterAttribute { private readonly ILogger _logger; public AppExceptionFilterAttribute(ILoggerFactory loggerfactory)...

ViewComponents in Areas

asp.net-mvc-6

The Area attribute can only be used with controllers. When you make a request to a view within an area and if this view has any view components referenced in them, then MVC looks for the view component's views in certain order. Following is the difference in how a view...

HandleUnknownAction in ASP.NET 5

asp.net-5,asp.net-mvc-6

There's no real equivalent. Action Selection in MVC5/WebAPI2 was a three stage process: 1. Run the routes 2. Select a controller 3. Select an action In MVC6, step 2 is gone. Actions are selected directly using route values - you'll notice that Controller.BeginExecute is gone as well. Controllers are 'thin'...

Using Startup class in ASP.NET5 Console Application

c#,asp.net-5,asp.net-mvc-6

What you're looking for is the right idea, but I think you'll need to back up a moment. Firstly, you may have noticed that your default Program class isn't using static methods anymore; this is because the constructor actually gets some dependency injection love all on its own! public class...

How do I get client IP address in ASP.NET 5 MVC 6?

asp.net-5,asp.net-mvc-6

You can use the IHttpConnectionFeature for getting this information. var remoteIpAddress = httpContext.GetFeature<IHttpConnectionFeature>()?.RemoteIpAddress; ...

How to publish a Asp.net 5 MVC6 website on IIS containing two web apps

asp.net-5,visual-studio-2015,asp.net-mvc-6

How did you deploy? Here are the steps that you can follow to get that running: Make sure that you the app pool is a .NET 4 app pool Run, in your web app's project folder dnu publish --runtime <name of runtime> (the name is the name of the runtime...

How to account for Properties.Settings.Default in ASP.NET 5

asp.net,asp.net-5,asp.net-mvc-6

There is no known way to make this work. See https://github.com/aspnet/Home/issues/591...

Anybody's had any luck with asp.net MVC 6's new html markup?

asp.net-mvc,razor,asp.net-5,asp.net-mvc-6

Make sure to include the helper library just below your model declaration @addtaghelper "Microsoft.AspNet.Mvc.TagHelpers" ...

Multiple Posted Types asp.net 5 MVC 6 API

c#,asp.net,asp.net-mvc,asp.net-5,asp.net-mvc-6

The best way is to create a composite wrapper: public class Wrapper { public ModelA A { get; set; } public ModelB B { get; set; } } Put Wrapper in the parameter list and mark that [FromBody]. You can't use that attribute more than once because all of the...

Create a method/function to use within a view

asp.net-5,asp.net-mvc-6

Referring to a few design discussions that we only have glimpses of online, @helper was removed for design reasons; the replacement is View Components. I'd recommend a View Component that looked like the following: public class ConfigurationKeysViewComponent : ViewComponent { private readonly IConfiguration config; public ConfigurationKeysViewComponent(IConfiguration config) { this.config =...

How to configure email settings in ASP.NET 5?

asp.net-5,asp.net-mvc-6

Try this as a way to keep your secrets secret. First, install the SecretManager and configure it with your secrets. When you're on your local machine, you'll want to use values from the SecretManager. With your hosting (e.g. in Azure) you'll use environmental variables. Local: Install and Configure the SecretManager...

Request.PhysicalApplicationPath in ASP-MVC 6?

asp.net-mvc,asp.net-mvc-6

You can use the ApplicationBasePath property on IApplicationEnvironment service to get this info. public class TestController : Controller { private readonly IApplicationEnvironment _appEnv; public TestController(IApplicationEnvironment appEnv) { _appEnv = appEnv; } public string Index() { return _appEnv.ApplicationBasePath; } } ...

Dependency injection (DI) in ASP.Net MVC 6

c#,asp.net-mvc,dependency-injection,asp.net-mvc-6

The differences between the two code blocks are indeed that the first one leverages Constructor Injection to resolve the dependency on TimeService, while the second example marks a property as one that needs resolving using Property Injection. What this means is simply that the following constructor becomes redundant: public HomeController(TimeService...

ASP.NET 5 Adding MVC6 Unit Test Project

asp.net,asp.net-mvc-6

this is my project.json that works with tests. { "version": "1.0.0-*", "dependencies": { "xunit": "2.1.0-beta1-*", "xunit.runner.aspnet": "2.1.0-beta1-*" }, "frameworks": { "aspnet50": { "dependencies": { } }, "aspnetcore50": { "dependencies": { "System.Runtime": "4.0.20-beta-22523" } } }, "commands": { "test": "xunit.runner.aspnet" } } ...

ASP.NET vNext AntiForgeryToken

asp.net-mvc-6,antiforgerytoken

The form tag helper will automatically add the anti forgery token. (Unless you use it as a standard html form element, manually adding an action attribute). Check the source code of the form tag helper, you will see the following at the end of the Process method. if (AntiForgery ??...

Using System.Net.Mail in ASP NET MVC 6 project

asp.net-mvc-6,system.net.mail

I don't believe that the SmtpClient is being ported to .Net Core. (You can use the unofficial reverse package lookup to find the new NuGet packages, and there isn't one.) Since you don't need .Net Core, you can remove the dnxcore50 entry from your frameworks in your project.json....

CORS for static HTML in vNext

cors,asp.net-5,asp.net-mvc-6

In Startup.cs Configure the policy in ConfigureServices ... public void ConfigureServices(IServiceCollection services) { options.AddPolicy("AllowEverything", builder => { builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod().AllowCredentials(); }); } Then in Configure set the app to use the policy, then set UseStaticFiles ... Ensure that UseStaticFiles() comes after UseCors - at least in the version I'm using (installed with...

Setup MongoDB in VNext

asp.net-mvc,mongodb,visual-studio-2015,asp.net-mvc-6

For some odd reason it works when I remove "aspnetcore50": { } from frameworks. Not sure what implications that will have { "webroot": "wwwroot", "version": "1.0.0-*", "exclude": [ "wwwroot" ], "packExclude": [ "**.kproj", "**.user", "**.vspscc" ], "dependencies": { "Microsoft.AspNet.Server.IIS": "1.0.0-beta1", "Microsoft.AspNet.Diagnostics": "1.0.0.0-beta1", "Microsoft.AspNet.Mvc": "6.0.0-beta1", "mongocsharpdriver": "1.8.3" }, "frameworks": { "aspnet50":...

HTTP Error 403.14 in ASP.NET5 MVC6

asp.net-mvc-6,vs-2015-preview

Try- public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddMvc(); } public void Configure(IApplicationBuilder app) { app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller}/{action}/{id?}", defaults: new { controller = "Home", action = "Index" }); }); } } ...

MVC 6 OpenIdConnect

asp.net-5,asp.net-mvc-6,openid-connect

The problem you are having is related to the Cookie header and it's beyond the limit of HTTP.sys if the 400 error you are getting is "HTTP Error 400. The size of the request headers is too long.". The Azure AD cookie header probably exceeds the limit for a single...

Unable to utilize UrlHelper

asp.net,asp.net-mvc-6

I have retrieved the IUrlHelper using the IServiceProvider in HttpContext.RequestServices. Usually you will have an HttpContext property at hand: In a controller action method you can do: var urlHelper = this.Context.RequestServices.GetRequiredService<IUrlHelper>(); ViewBag.Url = urlHelper.Action("Contact", "Home", new { foo = 1 }); In a filter you can do: public void OnActionExecuted(ActionExecutedContext...

How do I get the details of an Error 500 for an Azure Web App?

azure-web-sites,asp.net-mvc-6

For MVC 6 you need to add a web.config file to the wwwroot folder with the following: <configuration> <system.web> <customErrors mode="Off"/> </system.web> </configuration> That will add the markup to the deployed web.config file, and give you detailed errors. See http://docs.asp.net/en/latest/fundamentals/diagnostics.html#http-500-errors-on-azure for more details....

TagHelper for passing route values as part of a link

asp.net-5,asp.net-mvc-6,tag-helpers

You can use the attribute prefix asp-route- to prefix your route variable names. Example: <a asp-action="Edit" asp-route-id="10" asp-route-foo="bar">Edit</a>...

Future plans to consider for asp.net mvc 5.2 web application, with releasing asp.net mvc6 (vnext)

asp.net,asp.net-mvc,asp.net-mvc-5,asp.net-mvc-6,asp.net-mvc-5.2

I would simply recommend following the standard best practice of n-tier architecture and keeping logic related to things like querying a database in class libraries. MVC 6 is drastically different from previous versions, so there's no easy migration. You'll basically need to start a brand new project and move...

Getting Absolute URL's using ASP.NET MVC 6

c#,asp.net,.net,asp.net-mvc,asp.net-mvc-6

You could modify your extension class to use the IHttpContextAccessor interface to get the HttpContext. Once you have the context, then you can get the HttpRequest instance from HttpContext.Request and use its properties Scheme, Host, Protocol etc as in: string scheme = HttpContextAccessor.HttpContext.Request.Scheme; For example, you could require your class...

ASP.NET MVC 6 default debugging launch URL

asp.net-mvc-6

There was very little documentation that I could find regarding where this start up URL was declared. There is a brief mention of it in this blog post on MSDN. I eventually stumbled upon it in the launchSettings.json file under the Properties node of the project as shown below: Here...

Why using UseCookieAuthentication cause exception?

c#,asp.net,visual-studio-2015,asp.net-mvc-6

remove Security packages and add this: "Microsoft.AspNet.Authentication.Cookies": "1.0.0-beta4" and, in login/register controller var claims = new List<Claim> {new Claim(ClaimTypes.Name, model.Username)}; Context.Response.SignIn(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(new ClaimsIdentity(claims, "Cookies"))); ...

File IO Close() method error in ASP.NET MVC 6

asp.net-mvc,asp.net-mvc-6

Do you use the core CLR? The StreamWriter.Close method are not available in core CLR. You can use Dispose method replace. You also can use using statement: using (var writer = System.IO.File.CreateText("your_path")) { writer.WriteLine("text"); } ...

NET 5 MVC 6 - Publishing to Azure Websites ERROR_COULD_NOT_FIND_APPROOT_FOLDER

azure,asp.net-mvc-6

This has been fixed. You can follow the issue on github. https://github.com/aspnet/Tooling/issues/15...

ASP.NET 5 vNext Forms Having Anti Forgery Tokens Added

angularjs,asp.net-mvc-6

As of the time of this writing, that's just a bug in the Form tag helper. It will be fixed. You can exclude Form (or any element) from taghelper processing by adding a ! as in <!form></!form>...

TagHelper specify valid attributes

c#,asp.net,asp.net-mvc,asp.net-mvc-6,tag-helpers

With what you have right now (Attributes = AjaxForm) you'll get asp-ajax in your IntelliSense for form tags. If you want to also provide data-onsuccess in IntelliSense on form tags you can add another TargetElement attribute, aka: [TargetElement("form", Attributes = "asp-onsuccess")]. I want to note, that adding Attributes like this...

How to change PasswordValidator in MVC6

asp.net-mvc,asp.net-identity,asp.net-5,asp.net-mvc-6

The Solution In the Startup.cs write the code: services.ConfigureIdentity(options => { options.Password.RequireDigit = false; options.Password.RequiredLength = 6; options.Password.RequireLowercase = false; options.Password.RequireNonLetterOrDigit = false; options.Password.RequireUppercase = false; }); ...

Where are @Json.Encode or @Json.Decode methods in MVC 6?

asp.net-mvc,asp.net-mvc-6

After some search, found it: @inject IJsonHelper Json; @Json.Serialize(...) ...

Using Routing to return a WebForms page

c#,webforms,asp.net-5,asp.net-routing,asp.net-mvc-6

There is no support in ASP.NET 5 for Web Forms or the ASPX view engine. What you can do is redirect to a WebForm application on .NET 4.5/4.6, or better yet port your default.aspx to razor. As for the answer above - ASP.NET 5 does not yet support Web Pages....

How do I create Constructor Subscription in vNext Dependency Injection

c#,asp.net-mvc,dependency-injection,asp.net-5,asp.net-mvc-6

If you're wanting to resolve your Constraint through the Dependency Injection, you'll need to register it, first: services.AddTransient<Constraint>(); Once you have the IApplicationBuilder, you can access the services directly: app.ApplicationServices.GetRequiredService<Constraint>(); Of course, if you don't want to add your Constraint type to the services list, you can still access the...

db.database.ExecuteSQLCommand equivalent in EF 7

entity-framework,asp.net-5,asp.net-mvc-6,entity-framework-7

The feature isn't implemented yet. Track its progress using issue #624. Here is a crude extension method you can use for now. public static int ExecuteSqlCommand(this RelationalDatabase database, string sql) { var connection = database.Connection; var command = connection .DbConnection.CreateCommand(); command.CommandText = sql; try { connection.Open(); return command.ExecuteNonQuery(); } finally...

Publishing MVC 6 site with Visual Studio 2015 CTP 6 to IIS

iis-8,asp.net-5,visual-studio-2015,asp.net-mvc-6

It looks like there were some temp files created during the publish process that were not being deleted between versions. They were located at %temp%\AspNetPublish\[ProjectName], and deleting that folder removed the errors I was seeing as it cleared out all the old DLL files that shouldn’t have been published and...

ASP.NET 6 get RazorViewEngineOptions from app.ApplicationServices.GetService

c#,asp.net,asp.net-mvc-6

I believe you want an IOptions<RazorViewEngineOptions> type parameter on your GetService() call. Consider the ASP.NET Test Code here: https://github.com/aspnet/Mvc/blob/master/test/Microsoft.AspNet.Mvc.Razor.Test/RazorViewEngineOptionsTest.cs#L39 // Assert var accessor = serviceProvider.GetRequiredService<IOptions<RazorViewEngineOptions>>(); Assert.Same(fileProvider, accessor.Options.FileProvider); I am not readily able to verify this on my current workstation, and so not sure if this applies to ASP.NET MVC v6,...

ASP.NET 5 / MVC 6 Ajax post Model to Controller

c#,ajax,asp.net-5,asp.net-mvc-6

You need to explicit use FromBody on MVC6 if you are using json public JsonResult Login([FromBody]LoginViewModel model) EDIT I think you are mixing different errors. I will try to describe how you should make the request: content-type must be: application/json your request body must be in JSON format (as JasonLind...

Authentication in ASP.NET 5 (vNext)

asp.net,oauth,asp.net-5,asp.net-mvc-6

Microsoft.AspNet.Authentication.OAuth Allows 3rd party Identifiers (e.g. Google, Facebook) to authenticate users for you, saving your users the annoyance of registering. Allows other apps to use your application for Authentication Once your users are Authenticated by a 3rd party, the OWIN middle-ware reads their OAuth cookie and creates a domain specific...

Include several references on the second level

asp.net-mvc-6,entity-framework-7

.ThenInclude() will chain off of either the last .ThenInclude() or the last .Include() (whichever is more recent) to to pull in multiple levels. To include multiple siblings at the same level, just use another .Include() chain. Formatting the code right can drastically improve readability. _dbSet .Include(tiers => tiers.Contacts).ThenInclude(contact => contact.Titre)...

How to access HttpContext inside a unit test in ASP.NET 5 / MVC 6

asp.net,unit-testing,httpcontext,asp.net-mvc-6

Following are two approaches you could use: // Directly test the middleware itself without setting up the pipeline [Fact] public async Task Approach1() { // Arrange var httpContext = new DefaultHttpContext(); var authMiddleware = new MyAuthMiddleware(next: (innerHttpContext) => Task.FromResult(0)); // Act await authMiddleware.Invoke(httpContext); // Assert // Note that the User...

MVC 6 install as a windows service

asp.net-5,asp.net-mvc-6,dnx

I am afraid the answer is no for this. I have been looking into this as well and the best way to do this is to deploy your project into a known location on disk and have a Windows Service to spin up the process which calls the cmd file....

ASP.NET vNext - MissingMethodException: Method not found: Microsoft.CodeAnalysis.Diagnostic> EmitResult.get_Diagnostics()'

c#,.net,asp.net-mvc-6,vs-2015-preview,dnvm

I think David is right, I had the same issue and I was able to resolve it by: Opening the %USERPROFILE%\.dnx directory Deleting everything from the packages directory Deleting the beta5 directories from the runtimes directory Changing the value of the defaults.txt in the alias dir to point to one...

Entity Framework 7 group by

asp.net-5,asp.net-mvc-6,entity-framework-7

It doesn't look like this is currently supported, but it looks like someone saw this post and created the linked issue. The concept is a fairly complex bit of logic, and EF7 is very much in an early phase. .Net's GroupBy doesn't translate directly to SQL's GROUP BY until you...

Angular $http.post to a ASP MVC 6 Web Api

angularjs,post,asp.net-mvc-6

I should format json data as : $http.post('/api/account/login', { Email: vm.username, Password: vm.password, RememberMe: vm.rememberMe }) I should add [FromBody] directive in the API prototype : public async Task<IActionResult> Login([FromBody]LoginViewModel model) ...

Is controller scaffolding missing in MVC 6?

c#,asp.net-mvc-6,asp.net-mvc-scaffolding,vs-2015-preview

If you are referring to CRUD scafolding for controllers and views with ASP.NET 5 and MVC 6 it has been splitted off from the Visual Studio GUI and moved to command line. You'll need a package called CodeGenerators, add it to your project.json configuration file as: "dependencies": { ... "Microsoft.Framework.CodeGenerators.Mvc":...

How to get the current logged in user Id ASP.NET MVC6

asp.net,asp.net-identity,asp.net-mvc-6

I included using System.Security.Claims and I could access the GetUserId() extension method NB: I had the using Microsoft.AspNet.Identity already but couldn't get the extension method. So I guess both of them have to be used in conjunction with one another using Microsoft.AspNet.Identity; using System.Security.Claims; ...

Returning JSON Errors from Asp.Net MVC 6 API

json,asp.net-web-api,asp.net-5,asp.net-mvc-6

One way to achieve your scenario is to write an ExceptionFilter and in that capture the necessary details and set the Result to be a JsonResult. // Here I am creating an attribute so that you can use it on specific controllers/actions if you want to. public class CustomExceptionFilterAttribute :...

ASP.NET 5 MVC6 Custom CSS & Javascript placing convention

asp.net,asp.net-mvc-6

I do have app and vendor folders outside wwwroot. In vendor, I customize libraries like bootstrap, themes. In app I have my own css, less and js files for the application. I also have an asset path inside app for anything that needs to be copied (folder font shown in...

Syntactic sugar in Web Api - how to omit [FromBody]

c#,asp.net-mvc-6,syntactic-sugar

The model binding attributes in MVC 5 specify a "BindingSource" for each parameter on an action and can specify for each property on a controller, too. You can see specifically the code where it picks it up for the FromBody attribute in the BodyModelBinder Let me say first that you...

Access ASP.NET 5 View Component via URL

asp.net-5,asp.net-mvc-6

You cannot access a view component from a URL directly. A view component is just a component of a view and that view could be a regular or partial view. Based on your question, I believe you are trying to show the first page by default when the view (having...

What are asp.net vNext features? [closed]

asp.net,asp.net-mvc-6

What is asp.net vNext? ASP.NET vNext, which is an updated version of ASP.NET that been optimized for cloud Web development. You can reference The next generation of net asp.net vnext ASP.NET vNext will let you deploy your own version of the .NET Framework on an app-by-app-basis. One app with...

asp.net 5 mvc 6 model issue

asp.net-mvc,asp.net-mvc-6

It's because you are lazy loading the navigation properties. Look into this article. Just do this: var news = _db.News.Include(n => n.NewsCategory).ToList(); ...

How properly inject HttpContext in MVC6

asp.net-5,asp.net-mvc-6

If you are trying to access HttpContext, then you can use IHttpContextAccessor for this purpose. Example: services.AddTransient<QueryValueService>(); public class QueryValueService { private readonly IHttpContextAccessor _accessor; public QueryValueService(IHttpContextAccessor httpContextAccessor) { _accessor = httpContextAccessor; } public string GetValue() { return _accessor.HttpContext.Request.Query["value"]; } } Note that in the above example QueryValueService should be...

MVC 6 HttpPostedFileBase?

asp.net-mvc-6,httppostedfilebase

There is no HttpPostedFileBase in MVC6. You can use IFormFile instead. Example: https://github.com/aspnet/Mvc/blob/dev/test/WebSites/ModelBindingWebSite/Controllers/FileUploadController.cs Snippet from the above link: public FileDetails UploadSingle(IFormFile file) { FileDetails fileDetails; using (var reader = new StreamReader(file.OpenReadStream())) { var fileContent = reader.ReadToEnd(); var parsedContentDisposition = ContentDispositionHeaderValue.Parse(file.ContentDisposition); fileDetails = new FileDetails { Filename =...

How do I set the TypeScript compiler version for an ASP.NET 5 MVC 6 project in Visual Studio 2015 RC?

asp.net-5,visual-studio-2015,asp.net-mvc-6,typescript1.5

There is no way to do this in ASP.NET 5 natively. This is something you should handle inside gulp or grunt tasks. See this sample grunt task for typescript. It is based on the dependency you have for grunt typescript plugin.

asp.net 5 mvc 6 loginUrl change path

asp.net-mvc-6

Try doing the following: services.Configure<CookieAuthenticationOptions>(options => { options.LoginPath = new PathString("/<YOUR-AREA>/Account/Login"); } Question: Did you decorate your controller with an [Area] attribute?...