4
votes

I am trying to use 3 layered architecture in MVC MVC UI-->Services--> Entities

I am using built in asp.net web development server to this in which I configured port 4515 to run the UI layer and I am making ajax call to hit a webapi service in the service layer which is configured at port 35420.and when I make a ajax call I am getting an error like below with status 500

System.Net.Sockets.SocketException: No connection could be made because the target machine actively refused it 127.0.0.1:32450.

When I looked at the IIS express only 4515 is running and 35420 service layer is not running.

How to get rid of this problem? And I want my service layer to be running in parallel automatically, when my UI layer is running? Is there any way that I can accomplish a better solution for this?

And I am not able to configure same port number for this above two projects using built-in IIS Express built in development server for visual studio 2013?

Is it possible to do in IIS Express built in development server for visual studio 2013 to configure same port number for this above two projects?

Js function:

function AddProduct() {

    var productmodel = {
        ProductName: $('#ProductName').val(),
        CreationDate: $('#CreationDate').val(),
        ProuductSerialNumber: $('#ProuductSerialNumber').val(),
        Descripiton: $('#Descripiton').val(),
        CreatedBy: $('#CreatedBy').val(),
        Price: $('#Price').val()
    };
    var form = $("#productFrm");
    if (form.valid()) {
        $.ajax({
            url: 'Product/AddProduct',
            type: 'POST',
            data: JSON.stringify(productmodel),
            contentType: "application/json;charset=utf-8",
            beforeSend : function(xhr, opts){
                //show loading gif
                $(".overlay").show();
                $(".loading-img").show();
            },
            success: function (data) {
                if (data.StatusCode === 204) {
                    alert('Product Created Succesfully');
                }

                else
                {
                    alert('Something is wrong and server returned :' + data.StatusCode + ' and the reason is  ' + data.ReasonPhrase);
                }
            },
            error: function (x, y, z) {
                alert(x + '\n' + y + '\n' + z);
            },
            complete : function() {
                //remove loading gif
                $(".overlay").hide();
                $(".loading-img").hide();
            }
        });
    }
}


GloboMart.Application.Web.UI project Configured in IIS Port  4515:

public class ProductController : Controller
    {

        private HttpClient _client;
        private HttpResponseMessage _response;
        public ProductController()
        {
            _client = new HttpClient();
            _client.BaseAddress = new Uri("http://localhost:32450/");
        }
        // GET: Product
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public async Task<JsonResult> AddProduct(ProductViewModel ProductViewModel)
        {
            using (var client = _client)
            {
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));                
                StringContent content = new StringContent(JsonConvert.SerializeObject(ProductViewModel), Encoding.UTF8, "application/json");
                _response = await client.PostAsync("api/Products/CreateProduct", content);
            }
            return Json(_response);
        }

GloboMart.Services.WebApi project Confiugured in port http://localhost:32450/


using GloboMart.Domain.Entities.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using GloboMart.Application.Web.UI.Models;
using GloboMart.Domain.Entities.Entities;

namespace GloboMart.Services.WebApi.Controllers
{
    public class ProductsController : ApiController
    {
        private IProductRepository _repository;

        public ProductsController(IProductRepository Repository)
        {
            _repository = Repository;
        }

        // GET api/values
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/values/5
        [HttpGet]
        public List<Product> GetAllProducts()
        {
            var products= _repository.GetAll();

            return products.ToList();

        }

        // POST api/values

        [HttpPost]
        public void CreateProduct([FromBody] ProductViewModel ProductViewModel)
        {
            var Product=ConvertProductModelToProduct(ProductViewModel);
            _repository.Add(Product);
        }

        // PUT api/values/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/values/5
        public void Delete(int id)
        {
        }

        private Product ConvertProductModelToProduct(ProductViewModel ProductViewModel)
        {
          `enter code here`  var Product = new Product()
                                        {
                                           Name=ProductViewModel.ProductName,
                                           SerialNumber=ProductViewModel.ProuductSerialNumber,
                                           Description=ProductViewModel.Descripiton,
                                           CreatedBy=ProductViewModel.CreatedBy,
                                           CreationDate=Convert.ToDateTime(ProductViewModel.CreationDate),
                                           Price=ProductViewModel.Price
                                        };
            return Product;
        }
    }
}
2
You have multiple projects and all are started at debug: stackoverflow.com/questions/3697092/… ?rene
I assume the inconsistencies in port number (35420 and 32450) are typos rather than the fact you are trying to connect to the wrong port?Chris

2 Answers

0
votes

3 layer architecture doesn't mean you have to have 3 separately hosted layers.

You can put all the layers in one solution in Visual Studio. That way when you run your site, you can run it all at once as one hosted solution. Typically this is done with one Web/MVC project, a Application Logic project and a Dataaccess project (you called it entities). You should be able to pull in a reference in the Web/MVC project of the Application Logic project. Then you can pull in a reference of the Dataaccess into the Application Logic (or vise versa).

0
votes

it is perfectly normal to have applications which work like this : UI on a port and a webapi on a different port.

You have multiple ways of dealing with this.

  1. Both UI and WebApi are part of the same solution as separate projects. You know you can set one project to be the default so when you run the solution, one project runs automatically. You can right click the solution, go to properties then Common Properties and then select then select the multiple starting projects and select both projects you want, or even more than 2. Then both will run and be available when you run the solution.

  2. UI and WebAPi are in 2 different solutions. All you have to do is start the APi first, then start the UI and they will both run on their respective ports and be able to talk to each other.

Whichever solution you choose you can run and debug every layer independently.

Also you can make your life easier and configure each project to run in proper IIS instead of IIS express, then you won't get those crazy port number, it simplifies your life basically, plus it makes it easier because at some point you will need to deploy this stuff in proper IIS and you will simply replicate what you already have in dev