Quantcast
Channel: ASP.NET Core
Viewing all 9386 articles
Browse latest View live

I am at a lost as to why a simple Core2 WebApi dosen't work when published tto local IIS

$
0
0

I am doing a little project here to figure out how WebAPI Core2 is working. I have not figured out what is wrong.

If I am in VS using IIS Express, the I have no problems executing this simple code.

https://localhost:44382/api/cache

response = {"listDtoCache":[{"value":"Test1","text":"Vtest1"},{"value":"Test2","text":"Vtest2"}]}

using System.Collections.Generic;
using Entities;
using Microsoft.AspNetCore.Mvc;
using ProgMgmntCore2Api.Models;

namespace ProgMgmntCore2Api.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class CacheController : ControllerBase
    {
        [HttpGet]
        public CacheResponse Get()
        {
            //var resp = new CacheResponse {ListDtoCache = new List<DtoCache>()};

            return LoadResponse();
        }


        private CacheResponse LoadResponse()
        {
            var resp = new CacheResponse { ListDtoCache = new List<DtoCache>() };
            resp.ListDtoCache.Add(new DtoCache{Value = "Test1", Text = "Vtest1"});
            resp.ListDtoCache.Add(new DtoCache { Value = "Test2", Text = "Vtest2" });
            return resp;
        }
    }
}

But if I follow what is in the link and publish it, all I get is a error 404.

https://www.c-sharpcorner.com/article/publish-asp-net-core-2-0-application-on-iis/

ProgMgmntCore2Api.com/api/cache

If I use  browser address bar or Postmon it's 404 :)

if I enter ProgMgmntCore2Api.com, then I get the IIS page  talked about in the link, or I get a valid response in Postmon. So I know the app is listening. 

I am deep in the rabbit hole on the chase, I am now tired of this and need the resolution. :)


extract text from image with ocr in asp.net core2

$
0
0

Hi, I have develop a c# code with OCR which extract text from image. But when i convert same code into asp.net core 2.0. it failed and give me

"Method not found: 'System.Reflection.Emit.AssemblyBuilder System.AppDomain.DefineDynamicAssembly(System.Reflection.AssemblyName, System.Reflection.Emit.AssemblyBuilderAccess)'."

Have any one extract text from image in asp.net core 2.o with OCR? If yes then please post your code and name of libraries. and also post your project.

Thanks

Joining tables in two separate databases with .Net Core 2.1 / EF Core

$
0
0

I have a .Net Core 2.1 Web API which talks to two MySQL databases. Therefore I have two DbContexts, each with a connection string pointing to the relevant database.

In one of my controller actions, I need to return data which requires a join between two tables, one from each database. Is it possible to do this?

As an example, a simple controller action to retrieve data might look something like this:

[HttpGet]public IEnumerable<Employee> GetEmployees(){    return _context.Employees    .Include(e => e.Departments);}

That example uses one controller only, because in that example both the employee and department tables are in the same database, and therefore both their DbSets would be in the same DbContext.

But what if the employee table was in one database and department table was in another? Then the DbSets for employee and department would be defined in different DbContexts. How could I handle the join in that case? (So that in the example above, the "Include" works properly?

I would imagine that I would have to inject both DbContexts into this controller. But I'm not sure where to go from there...

In my case, both datbases are MySQL databases, and both are on the same server, so that is the only scenario I'm interested in.

Deployment Issues with my First ASP.NET Core application

$
0
0

Dear Friends,

I am still having issues with running my first ASP.NET WebAPP. While launching my web app from Visual Studio 2017, I get web page (at http://172.20.43.21/) with error:

The Web page cannot be found.

Although output window shows messages like: Now listening on: http://[::]:80 and Request starting HTTP/1.1 GET http://172.20.43.21/ 

My docker-compose.override.yml is as follows:

version: '3.4'

services:
xmltocsv:
image: xmltocsv:latest
build:
context: .
dockerfile: UploaderParserApi\Dockerfile
environment:
- ASPNETCORE_ENVIRONMENT=Development
ports:
- "6001:80"

uploaderapi:
image: parserapi:latest
build:
context: .
dockerfile: UploaderParserApi\Dockerfile
environment:
- ASPNETCORE_ENVIRONMENT=Development
ports:
- "6001:80"

networks:
default:
external:
name: nat

What is code does, simply calls uploader API from ASP.MCV app.

Any help or suggestion where I can see logs will be appreciated.

Thanks,

Pervaiz Khan.

Clarification of Meaning of .Net Core Framework

$
0
0

If someone asked you to build a pizza delivery system  and asked that you use .Net Core framework?

Would this be the .Net framework 4.6 or .Net Core 5 and   what would each stack consist of?

How to specify Etag or Last-Modified header for images that ImageSharp Generates (Crop & Resized)

$
0
0

Hello.

I am using ImageSharp for crop and resize on the fly in ASP.NET Core.

I have an API :

[HttpGet("/image/{width:int:min(0)}/{height:int:min(0)}/{*url}")]
        public async Task<IActionResult> ResizeImage(string url, int width, int height)
        {
            if (width < 0 || height < 0 ) { return BadRequest(); }
            if (width == 0 && height == 0) { return BadRequest(); }

            var key = $"/{width}/{height}/{url}";
            var data = await _cache.GetAsync(key);
            if (data == null)
            {
                var imagePath = PathString.FromUriComponent("/" + url);  
                var fileInfo = _fileProvider.GetFileInfo(imagePath);  
                if (!fileInfo.Exists) { return NotFound(); }

                data = ips.CropResize(fileInfo,height,width);

                const int durationInSeconds = 60 * 60 * 24 * 7;
                ctx.HttpContext.Response.Headers[HeaderNames.CacheControl] =
                "public,max-age=" + durationInSeconds;
                var cacheEntryOptions = new DistributedCacheEntryOptions()
                .SetSlidingExpiration(TimeSpan.FromHours(7));
                await _cache.SetAsync(key, data,cacheEntryOptions); 
            }

and i have a CropResiz method :

public byte[] CropResize(IFileInfo fileInfo,int height,int width)
        {
            using (var outputStream = new MemoryStream())  
            {
                using (var inputStream = fileInfo.CreateReadStream())
                {
                    using (var image = Image.Load(inputStream))
                    {
                        var currentW = image.Width;
                        var currentH = image.Height;
                        if(currentW > currentH)
                        {
                            image
                            .Resize(0,height);
                            var resizedW = image.Width;
                            var cropX = (resizedW / 2) - (width / 2);
                            var resizedH = image.Height;
                            var cropY = (resizedH / 2) - (height / 2);

                            image
                            .Crop(new Rectangle(cropX, cropY, width, height))
                            .SaveAsJpeg(outputStream,new JpegEncoder(){Quality = 80});
                        }
                        else
                        {
                            
                            image
                            .Resize(width,0);

                            var resizedW = image.Width;
                            var cropX = (resizedW / 2) - (width / 2);
                            var resizedH = image.Height;
                            var cropY = (resizedH / 2) - (height / 2);

                            image
                            .Crop(new Rectangle(cropX, cropY, width, height))
                            .SaveAsJpeg(outputStream,new JpegEncoder(){Quality = 80});
                        }
                    }
                }

                return outputStream.ToArray();
            }
        }

Now it works fine, but the problem is when i check my website in GTmetrix.com i get Specify a cache validator error for this images.

Exactly images that i request by ImageSharp api.

Anybody can help me to know how can i specify cache validator to this images?

LINQ query parameter expression exception

$
0
0

Hey guys I got this error while debugging with my code (SEE CODE at the bottom): 

Any Ideas to fix this woul dbe great, from what I have researched it has to do with a bug in EF Core. SEE Reference Click Here though I am not sure how to fix my own code...

System.InvalidOperationException
HResult=0x80131509
Message=An exception was thrown while attempting to evaluate a LINQ query parameter expression. To show additional information call EnableSensitiveDataLogging() when overriding DbContext.OnConfiguring.
Source=Microsoft.EntityFrameworkCore

Inner Exception 1:
NullReferenceException: Object reference not set to an instance of an object.

My code

        [BindProperty]
        public OrderDetailsCart DetailCart { get; set; }

        public void OnGet()
        {
            DetailCart = new OrderDetailsCart()
            {
                ListCart = new List<ShoppingCart>(),
                OrderHeader = new OrderHeader()
            };
            DetailCart.OrderHeader.OrderTotal = 0;
            var claimsIdentity = (ClaimsIdentity)this.User.Identity;
            var claim = claimsIdentity.FindFirst(ClaimTypes.NameIdentifier);

            var cart = _context.ShoppingCart.Where(c => c.ApplicationUserId == claim.Value);
            if (cart != null)
            {
//Throws the error! DetailCart.ListCart = cart.ToList(); } foreach (var list in DetailCart.ListCart) { list.MenuItem = _context.MenuItem.FirstOrDefault(m => m.Id == list.MenuItemId); DetailCart.OrderHeader.OrderTotal += (list.MenuItem.Price * list.Count); if (list.MenuItem.Description.Length > 100) { list.MenuItem.Description = list.MenuItem.Description.Substring(0, 99) + "..."; } } DetailCart.OrderHeader.PickUpTime = DateTime.Now; }

Angular with .Net Core

$
0
0

Hi Friends,

I was wanting to use Angular with .Net Core. Are there any good resources covering this? Thanks !


Displaying Success/Error message from a common view which be can reused/injected in all over the application

$
0
0

am working on displaying success and error messages after the form is submitted. I created a separate view for error message and trying to inject it all the pages as partial view.Its not working now. Is there any other way to achieve this or any example  available for this. Thanks in advance.

Check if foreign ID still exits - how to approach

$
0
0

Hello,

So I have a project where i for an example have this class

        public int SupportTeamID { get; set; }
        [Required]
        public int ContactInformationID { get; set; }
        [Required]
        public string SupportTeamName { get; set; }

        public IEnumerable<ContactInformation> ContactInformations { get; set; }
         public IEnumerable<SupportTeam> SupportTeams { get; set; }

    }
}

As you can see it uses the ID of two other entities.

But as it is now in my view, I can set it to an existing ContactInformationID, then delete that ContactInformationIDin the ContactInformation view  and now the Supportteam has an ID to a non existing ContactinformationID. 

I'm not sure what the general approach to this is, can anyone provide me some guidance?

Thanks in advance.

How to pass API Credentials in HttpClient.

$
0
0

Hi,

I am porting code from asp.net to asp.net core where I need to send REST API credentials. But I am getting Unauthorized error. 

Here is the logic: Let me know what is missed here

ASP.NET Code:

Uri myUri = new Uri(requestAddress);
string host = myUri.Host; // host is "www.contoso.com" ;

var client = new RestClient("https://" + host);

client.Authenticator = new HttpBasicAuthenticator(qualysUser, qualysPass);
var request = new RestRequest("api/2.0/fo/scan/", Method.POST);
request.AddHeader("X-Requested-With", "RestSharp");
request.AddParameter("action", "launch");
request.AddParameter("option_title", Profile);
request.AddParameter("scan_title", title);
request.AddParameter("iscanner_name", scanner);
request.AddParameter("ip", IPs);
//  
var response = client.Execute(request);
//eventLog1.WriteEntry("Response : " + response.ToString());
string resultx = response.Content;
//eventLog1.WriteEntry("Scan Response Recieved :" + resultx.ToString());
XmlDocument doc = new XmlDocument();
doc.LoadXml(resultx);
XmlNodeList nodelistx = doc.SelectNodes("/SIMPLE_RETURN/RESPONSE/ITEM_LIST/ITEM");

foreach (XmlElement node in nodelistx)
{
result = node.ChildNodes.Item(1).InnerText.ToString();
}

ASP.NET CORE

var credentials = new NetworkCredential(qualysUser, qualysPass);
var handler = new HttpClientHandler { Credentials = credentials, UseDefaultCredentials = true };

using (var client = new HttpClient(handler))
{
string result = string.Empty;

Uri myUri = new Uri(requestAddress);
client.DefaultRequestHeaders.Add("X-Requested-with", "RestSharp");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.BaseAddress = myUri;

var parameters = new Dictionary<string, string> { { "action", "launch" },
{ "option_title", Profile }, {"scan_title", title }, { "iscanner_name", scanner }, {"ip", IPs } };

var encodedContent = new FormUrlEncodedContent(parameters);

var response = await client.PostAsync(myUri, encodedContent).ConfigureAwait(false);
if (response.StatusCode != HttpStatusCode.OK)
{
return "";
}

var responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
XmlDocument doc = new XmlDocument();
doc.LoadXml(responseContent);
XmlNodeList nodelistx = doc.SelectNodes("/SIMPLE_RETURN/RESPONSE/ITEM_LIST/ITEM");
foreach (XmlElement node in nodelistx)
{
result = node.ChildNodes.Item(1).InnerText.ToString();
}

return result;

How to use CK Editor 5 with Asp.Net Core

$
0
0

Hi,

How to use CK Editor 5 with Asp.Net Core ? I found this script

<textarea asp-for="FaqCustomer.Answer" class="form-control Answer" rows="6"></textarea><script src="~/ckeditor5/ckeditor.js"></script><script>
                                    ClassicEditor
                                        .create(document.querySelector('#FaqCustomer_Answer'), {
                                            ckfinder: {
                                                uploadUrl: '@Html.Raw(Model.Setting.UploadUrl)'
                                            }
                                        })
                                        .catch(error => {
                                            console.error(error);
                                        });</script>

                               
//UploadUrl=https://cksource.com/[key]/core/connector/php/connector.php?command=QuickUpload&type=Files&responseType=json

I have 3 question.... 

1- how can I upload file in my local folder. Example is about cksource server... you can upload there.... and I mean you have to member there... Can I create my own upload script and use it in here ? do you have any example about that ?

2- how to disable this editor ? this is not working : document.getElementById("FaqCustomer_Answer").disabled = true;

@section scripts{<script type="text/javascript">$(document).ready(function () {
            alert("test message");
            document.getElementById("FaqCustomer_Answer").disabled = true;
        });</script>
}

3- How to use placeholder message in this editor ? 

Question about data annotations

$
0
0

Hello! I am creating a website on asp.net core, and I have a problem understanding how I should use data annotations. So, I have a model with six properties. Four out of those six properties, I absolutely need the user to fill them in, through a View that I created. The last two, I need them as well, but I don't want the user to fill them in, but I have to do it when the request will be submitted. So, should I add the [required] attribute on the two properties that I need to be submitted, and remove them from the user sight through a View Model, or I should leave them as they are ?

Can't get ViewComponent Default.cshtml to show up

$
0
0

Hello,

I have an Asp.Net Core 2.1, MVC, C# Web application in Visual Studio 2017 15.7.5 using a ViewComponent invoked directly from a controller.

When It gets to the return View(items); it does not show on the screen.

It does display the alert in the startTask() function and shows the alert data.

When I use the Developer Tools/Network tab, it shows the Get for /products/ Response Payload as having the data for the display of the view as indicated by this screen shot. It seems that the information is there, it just doesn't show on the screen.

I did try these returns:

return View("Default", items);
return View("~Views/Shared/Components/ProductList/Default.cshtml", items);

Here is my code:

ProductListViewComponent.cs

namespace ChinavasionAPI.ViewComponents
{
    public class ProductListViewComponent : ViewComponent
    {
          private readonly ChinavasionAPIContext _context;
          private readonly IHubContext<ChvHub> _hubContext;

          public ProductListViewComponent(IHubContext<ChvHub> hubcontext, ChinavasionAPIContext context)
          {
               _context = context;
               _hubContext = hubcontext;
          }

          #region snippet1
          public async Task<IViewComponentResult> InvokeAsync()
          {
               var items = await GetItemsAsync();
               await this._hubContext.Clients.All.SendAsync("ReceiveMessage", "", "===============================================  Ready to Display Lakeside and Chinavasion Products  ===============================================");
               return View(items);
          }

          public async Task<List<ProductViewModel>> GetItemsAsync()
          {
               var model = new AccessModel();
               model.UserAccessModel = _context.UserAccessModels.Single(a => a.ID == 1);

               // Most of the code taken out for brevity..........

               await this._hubContext.Clients.All.SendAsync("ReceiveMessage", "", "==================================================  Merging Lakeside and Chinavasion Products  ==================================================");
               var result =
                    from c in multipleProductModel.MProductsApi
                    join p in multipleProductModel.MProducts on c.Sku equals p.model_code into ps
                    from p in ps.DefaultIfEmpty()
                    select new ProductViewModel
                    {
                         Id = c.Id,
                         Sku = c.Sku,
                         //Categories = c.Categories,
                         product_id = p?.product_id != null ? p.product_id : 99999,
                         model_code = p?.model_code != null ? p.model_code : "Not found",
                    };

               ViewData["ChvProductCount"] = multipleProductModel.MProducts.Count.ToString();
               ViewData["ChvProductNotFoundCount"] = chvProductNotFoundCount.ToString();

               return result.ToList();
          }

AccessToken.cshtml:

@model ChinavasionAPI.Models.AccessModel
@using Microsoft.AspNetCore.Http.Extensions

@{
     ViewData["Title"] = "Access Token";
}

@section Scripts {
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script><script src="~/lib/signalr/signalr.js"></script><script src="~/js/chat.js"></script>
}<div><h2>Access Data</h2>
     @using (Html.BeginRouteForm("Submit", FormMethod.Post))
     {<table><tr><td><label for="serverUrl">Server url: </label></td><td><input style="margin-left:6px;width:400px;" name="serverUrl" type="text" id="serverUrl" value="@Model.UserAccessModel.ServerUrl" /></td><td> </td><td> </td><td><input style="margin-left:6px;" type="submit" value="Get Access Token" /><button style="margin-left:6px;" type="button" id="refresh-token-button">Refresh Access Token</button></td>

@* Most code taken out for brevity *@

<div class="container"><div class="row"><div class="col-md-5"></div><div class="col-md-2"><button class="btn btn-default" id="get-products-button" value="Get Products" style="margin-top:5px" ; onclick="startTask()">Get Products</button></div><div class="col-md-5"></div></div><div class="row" style="background-color:#efefef;"><br /><div class="col-md-12"><ul id="messagesList"></ul></div></div></div><script>
     function startTask() {$.get("/products/", function (data) { alert(data); });
     }</script><script>

     document.getElementById("get-products-button").addEventListener("click", event => {
          event.preventDefault();
     });</script>

Default.cshtml: (This is in \Views\Shared\Components\ProductList)

@model List<ChinavasionAPI.Models.CAPIViewModels.ProductViewModel>

@{
     ViewData["Title"] = "products";
}<h2>Products List</h2><div class="container-fluid"><table class="table table-hover table-bordered table-striped"><thead><tr><th colspan="2" scope="colgroup">Lakeside products  =  @Model.Count.ToString()</th><th></th><th></th><th colspan="2" scope="colgroup">Chinavasion products  =  @ViewData["ChvProductCount"]</th></tr><tr><th>Product ID</th><th>Sku</th><th></th><th>Product ID</th><th>Model Code</th></tr></thead><tbody>
               @foreach (var item in Model)
               {<tr><td><span>@item.Id</span></td><td><span>@item.Sku</span></td><td><span></span></td><td><span>@item.product_id</span></td><td><span>@item.model_code</span></td></tr>
               }</tbody></table></div>

ProductsController.cs:

namespace ChinavasionAPI.Controllers
{
    public class ProductsController : Controller
    {
          private readonly ChinavasionAPIContext _context;

          public ProductsController(ChinavasionAPIContext context)
          {
               _context = context;
          }

          public async Task<IActionResult> GetProducts()
          {
               return ViewComponent("ProductList");

          }

Does anyone know why that Default.cshtml will not display?

Thanks,
Tony

System.Threading.Timer Advice Needed

$
0
0

Hello,

I am learning ASP.NET Core and C# by building a poker web app. I created an ASP.NET Core 2.0 Web Application project and set up RESTful routing and dbcontext to allow my project to interact with a local SQL database that I am running on MSSQL Server. I have verified that I can Create, Read, Update and Delete records in the database by sending the appropriate HTTP requests with Postman. I have also created a couple of poker related classes for the purposes of randomly generating poker hands, comparing the hands, and ranking the hands based on the rules of poker as this will be a necessarily functionality for the game. Now what I want to do is set up some code that will execute at a recurring interval on application startup so I can randomly generate poker hand data and log it to my database so I can analyze a couple hundred thousand hands with SQL to verify that I have appropriately captured the logic of poker in my poker related classes. I was able to get this to work using System.Threading.Timer as shown in the class below, with which I construct and call the Start method on application startup, but I am curious if there's a better way to meet my goal or if my code could be improved. Here's what I have so far:

using System.Collections.Generic;
using System.Threading;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using PokerApi.Controllers;

namespace PokerApi.Models
{
    public class PokerDataTimer
    {
        private IConfiguration Configuration { get; }
        private Timer timer { get; set; }

        public PokerDataTimer(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public void Start()
        {
            timer = new Timer(new TimerCallback(GenerateAndLogHandData), null, 0, 1000);
        }

        private async void GenerateAndLogHandData(object timerState)
        {
            var optionsBuilder = new DbContextOptionsBuilder<HandDataContext>();
            optionsBuilder.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));

            using (var context = new HandDataContext(optionsBuilder.Options))
            {
                var handData = new HandGenerator().Play(); // Generates poker hand data
                var handDataController = new HandDataController(context);
                await handDataController.PostHandData(handData);
            }
        }
    }
}

Some specific questions I have:

1) Is System.Threading.Timer the right class to use here? I have a JavaScript background and was looking for something that would function the same as JavaScript's setInterval, but after going down a rabbit hole of reading about timers and threading in C#, I learned that there isn't an obvious equivalent. From everything I read, System.Threading.Timer sounded like the right choice, especially for ASP.NET Core.

2) It strikes me as inefficient to repeatedly create new dbcontext and controller instances in each iteration of my timer. However, I couldn't figure out how to create those objects first and then pass them into the TimerCallback. I see the TimerCallback takes an optional timerState object that can be passed as the second argument in the Timer constructor, but I couldn't figure out how to pass my dbcontext and/or controller into the GenerateAndLogHandData method in this way. Without being able to set them globally on the class or pass them into the TimerCallback, I felt my only option was to create and use them on each iteration of the timer. This works, but is there a better way?

Thanks in advance,

Eric


AAD B2C - .NET Core 1.1 Web API authenticates but the .NET Core 2.0 version returns 401.

$
0
0

For the past year I've been hosting a Web API built with ASP.NET Core 1.1. I recently implemented a new version of the Web API using .NET Core 2.0 but its failing authentication. Following are the relevant code snippets from the working (1.1) and failing (2.0) project Startup.cs files.

.NET Core 1.1

// Startup.Configure Method
app.UseJwtBearerAuthentication(new JwtBearerOptions()
{
	Audience = Configuration["aad:clientId"],
	AutomaticAuthenticate = true,
	AutomaticChallenge = true,
	MetadataAddress = Configuration["aad:MetadataAddress"]);
});

.NET Core 2.0

// Startup.Configure Method
app.UseMvc().UseAuthentication();

// Startup.ConfigureServices Method
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
	.AddJwtBearer(options =>
	{
		options.Audience = Configuration["aad:clientId"];			
		options.MetadataAddress = Configuration["aad:MetadataAddress"]);
	});

doc.microsoft documentation says AutomaticAuthenticate/Challenge have been removed and the default schema (JwtBearerDefaults.AuthenticationScheme) should be used for authentication and challenges.

I'm obviously missing something but I'm not sure what at this point.

Any input you might have will be appreciated.

Thanks,

Dane Vinson

How to add services in startup only in development

$
0
0

So i have in my Configure method in Startup.cs the usual 

if (env.IsDevelopment())
{
     app.UseBrowserLink();
     app.UseDeveloperExceptionPage();
     app.UseDatabaseErrorPage();
}
else
{
     app.UseExceptionHandler("/Home/Error");
     app.UseHsts();     
}   
app.UseHttpsRedirection();

But how do I regulate this in the ConfigureServices method? I don't want to specify the httpsredirectionmethod i use on  the live server because the port is different and i don't want to add hsts to the cointainer in development because it could be cached in the browser then.

Ideally I want to use HttpRedirection in development, but then specify a different port. Is this possible? Or does it even matter 

In ConfigureServices I use this currently (In development I just comment out the AddHsts and AddHttpRedirection calls but this is annoying to do each time):

//services.AddHsts(options =>
//{
//    options.Preload = true;
//    options.IncludeSubDomains = true;
//    options.MaxAge = TimeSpan.FromDays(30);
//});
//services.AddHttpsRedirection(options =>
//{
//    options.RedirectStatusCode = StatusCodes.Status301MovedPermanently;
//    options.HttpsPort = 443;
//});

Can't Migrate Entity FrameWork

$
0
0

Hello

I run this command on package manager console :

pm>Enable-Migrations

But keep getting this message:

Object reference not set to an instance of an object.

What is wrong? Please inform me.

regards,

saeed

Dependency Injection with HTTPPost

$
0
0

Hi guys,

I am trying to do simple injection of the Address Class.

public class Address : IAddress
{
  public string City { get; set; }
}

Following interface

	public interface IAddress
	{
		string City { get; set; }
	}

ConfigServices

public void ConfigureServices(IServiceCollection services)
{
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

	services.AddScoped<IAddress, Address>();
	services.AddScoped<IMetrics, MetricsMockup>();
}

When I use DI in constructor it is working

    public class NodesController : ControllerBase
    {
	public IAddress Address;

	public NodesController(IAddress address)
	{
		Address = address;
	}

However, when I am trying to do the same in Post I am getting the error

        [HttpPost]
        public ActionResult<NodeEntity> Post([FromBody] IAddress entity)
        {
		var a = entity;
		return Ok();

        }

What am I missing? 

I am using Fiddler to execute the request. If I am using Address instead of the IAddress, everything is working.

Asp.Net Core 2.1 MVC Web app - HTTP Error 502.5 - Process Failure error from VS2017 and IIS

$
0
0

I have been building a Asp.Net Core 2.1 MVC web app for several months on two differnt windows PCs. I have been able to code, debug and test this app hundreds of times on both PCs without issue. On the same PC where I was coding and testing all dayyesterday without any issues, today all of a sudden I keep getting HTTP Error 502.5 - Process Failure error when I build and run the app from VS and IIS. I have read so many postings for this error, nothing seems to work! This has happened in the past a few times and all I did was restart my PC and then it seemingly went away. I am completely stumped as to how to get past this error. I have lost my entire day to this issue! 

I published the app to my local IIS instance and ran the app there and I get the same error message from there too! The other real frustrating part is, I cannot get the AspNetCore logs to generate anything from IIS site. Here is the web.config setting for logs:

<aspNetCore processPath=".\Remodel21.Web.Mvc.exe" stdoutLogEnabled="true" stdoutLogFile=".\logs\stdout" />

When I run the app the log files are not getting created!! 

When I look at the event viewer on my PC, I keep seeing the error message below each time I get the 502.5 error.

Log Name:      Application
Source:        IIS AspNetCore Module
Date:          7/28/2018 4:30:58 PM
Event ID:      1000
Task Category: None
Level:         Error
Keywords:      Classic

Application 'MACHINE/WEBROOT/APPHOST/DOTNETCORE21' with physical root 'C:\inetpub\wwwroot\RemodelApp\' failed to start process with commandline 'C:\inetpub\wwwroot\RemodelApp\Remodel21.Web.Mvc.exe ', ErrorCode = '0x80004005 : 0.

I hope someone can help me out here, its imperative that I get my app working again on this PC. It is primary PC for doing all my development. I have so much code on this PC.

Viewing all 9386 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>