Query MVC Web Api from another project while running on localhost - asp.net-mvc

I have a Vis Stu solution that contains many projects. Two of these projects are a
MVC Web Application (Views, JS, CSS)
MVC Web API
Since these are their own projects, I need a way to query the Web Api via my web application.
In the JS I have a function that tries to get data from the Web Api
get: function (id) {
var url = 'api/Employee/' + id;
var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function (data) {
return data;
};
httpRequest.open('GET', url);
httpRequest.send();
}
If I build the Api solution and add in its localhost address to the ajax url (http://localhost:50475/api/Employee/3) I get the usually Cross Origin Not Allowed issue.
Is there a way to connect to this Api from another origin while I am in developing?

Have you tried adding an assembly reference to your project? That will make projects accessible to each other in development.
In visual studio:
1. Go to the project that needs to have access to the API project
2. Right click references
3. Add reference
4. Under Solution select the name of the project you're trying to access.

I Think its because of different ports of WebApi and MVC Projects that visual studio assigned to them by default. you can change the default port bindings, You should set one unique port for both applications. Right click on project => properties => web and set the port.

Related

ASP.NET Core Identity for multiple project with IdentityServer4

I have one solution with two MVC projects, which use the IdentityServer4. In one project I installed the IdentityServer4 and have full access to the database. The other project is an MVC client.
When I set the [Authorize] attribute on both project all works fine, but this role attribute [Authorize(Roles = "user")] works only in project one that has the IdentityServer4, the MVC client says:
Unable to resolve service for type 'Microsoft.AspNetCore.Identity.UserManager`1[Entities.Application.ApplicationUser]' while attempting to activate 'IdMWeb.Controllers.AccountController' (this is the project one with the IdentityServer4 installed).
My questions are, why project one does not complain when I do not set the role attribute in project 2.
Also, how can project 2 get the role from the database?
please see bottom link for asp .net core apps:
Share authentication cookies path
simple answer:
please add bottom code in startup.cs ConfigureServices method of two or more ASP.NET Core projects :(be cureful the path "C:\sampleDirectoryInServer" exists in your server)
services.AddDataProtection()
.PersistKeysToFileSystem(new DirectoryInfo(#"C:\sampleDirectoryInServer"))
.SetApplicationName("SharedCookieApp");
services.ConfigureApplicationCookie(options => {
options.Cookie.Name = ".AspNet.SharedCookie";
});
it's work for me(2 asp.net core app with same database and different ports)
Based on the error message your posted, It may be that you did not define a client on the server side for this particular client. A IdentityServer instance will only accept requests from clients that it already knows about. You have to define the acceptable clients for it when you configure the middleware.

MVC Web App using Web API do not work after deploying on IIS

I have created Web application using asp.net MVC architecture.
I have used Web API for getting data from database. Both Web application and Web API are in same project. I have not published Web API separately on IIS.
When I am debugging or running the application through Visual studio it works properly. I have used below code to get data from Web API URL
TODOINfo[] lstToDoInfo = httpClient.GetAsync("http://localhost:65373/api/RESTApi").Result.Content.ReadAsAsync<TODOINfo[]>().Result;
In Above function I am passing url which consist of localhost plus fixed port number. Above code is working fine when running through in Visual studio.
I have published the same code on IIS by doing below changes.
TODOINfo[] lstToDoInfo = httpClient.GetAsync("http://" + sBaseUrl + "/api/RESTApi").Result.Content.ReadAsAsync<TODOINfo[]>().Result;
sBaseUrl value is "localhost".
After Browsing the application on internet explorer getting following error.
No MediaTypeFormatter is available to read an object of type 'TODOINfo[]' from content with media type 'text/html'.
Any information or suggestion regarding above problem is highly appreciate.
Try changing sBaseURL to "localhost/" +yourwebsite
another option would be to change: sBaseURL to: servername/yourwebsite

Calling Web API from MVC Application when both in same Solution

So I am totally new to the Web API and I thought to myself I would start a test project to learn it and AngularJS and how they can work together nicely ... etc.
I have created a multi-tier architecture within my solution, and inside my TPlan.API project, I have the following route configured in the Global.asax
GlobalConfiguration.Configuration.Routes.Add("default",
new HttpRoute("api/{controller}"));
TPlan.WEB is my MVC application, and it is set up as "Start Up Project". When I run it, I want to be able to go to:
mysite:port/api/test
And get the value from the API from my test controller in there.
However it is not working for me, I get the following:
No HTTP resource was found that matches the request URI 'mysite:port/api/test'.
Er, in visual studio, right click on the solution and go to properties.
Go to startup and select the "multiple projects" option and tick the website and the webservice to both start up.
That will start both of them. But as has been pointed out, they're running on separate ports, they're completely separate applications...
I don't think you can register a route that belongs outside of the website.
We work like this
View => POST / GET => MVC Controller => HTTP Request => API Controller
So our mvc views post or get to our mvc controllers, and then we fire off a separate http request to the web api. this is a server to server call, its like calling any external web service. we wait for the response from the api and then return whatever is required to the view...
What you are attempting isn't logically possible without installing your WebAPI project into IIS ahead of time, which I'm sure is not what you want. Both projects cannot be run at the same time, as only one project will be able to launch a debug session of IIS Express. Even if both projects were able to run at the same time, they would be on different logical ports, and routing from one project would have to be manually sent to the listening port of the other instance. Basically, your Global.asax on your API project will never run, as that project will be built as a class library.
Make your TPlan.API project a simple Assembly, reference it from TPlan.Web and pass the GlobalConfiguration.Configuration property over to a Register method that is in your API assembly. When the MVC project starts, both the MVC routes and the Web Api routes will be active on the same web host.
Here is an example of an API that has both a console host and a web host in the same solution.
Please check the following site. I believe the issue lies in the configuration of the route
http://www.asp.net/web-api/overview/extensibility/configuring-aspnet-web-api

Can't access webservice using Xamarin and WCF

I would like to consume a public web service using Xamarin and WCF. For this demo, I'll be using Xamarin.iOS .
This is the (public) webservice I'm trying to consume:
http://www.webservicex.net/globalweather.asmx?WSDL
Inside Xamarin Studio, I add a Web Reference with the URL from the webservice. The selected Framework is set to Windows Communication Foundation (WCF).
Now, I'm using the following code to connect with the service:
var _client = new GlobalWeatherSoapClient();
_client.BeginGetWeather ("Berlin", "Germany", (ar) => {
var result = _client.EndGetWeather(ar);
}, null);
When executing this code, I'm getting a System.NullReferenceException. This is the problem, why isn't it working correct?
The strangest part: When I'm not using WCF, but select .NET 2.0 Web Services as Framework, everything seems to be working fine.
I can't see what's wrong with my WCF code - according to the docs, everything should work ok.
I hope somebody can help me out! Thanks in advance!
You are not following the docs.
Quote from that page:
To generate a proxy to a WCF service for use in Xamarin.iOS projects,
use the Microsoft SilverlightServiceModel Proxy Generation Tool
(SLSvcUtil) that ships with the Silverlight SDK on Windows. This tool
allows specifying additional arguments that may be required to
maintain compliance with the service endpoint configuration.
So, first thing is that you need to create a proxy on a Windows machine with slsvcutil. Adding WCF references to project through Xamarin Studio does not work. It only works for .NET 2.0 Web Services, that's why that option is OK.
Second thing, after you have created your proxy on Windows with slsvcutil, you need to add it to your project.
Third, you need to initialize it like this, with basic http binding (again, code from the above link):
var binding = new BasicHttpBinding () {
Name= "basicHttpBinding",
MaxReceivedMessageSize = 67108864,
};
//...
client = new Service1Client (binding, new EndpointAddress ("http://192.168.1.100/Service1.svc"));
Suggestion: forget about WCF on iOS. That article contains very useful information on other means of client-server communication.

Breeze sample does not work in IE

I create a MVC 4 application (WebAPI or empty) and I load the Breeze NuGet packages and hit F5 like they say I should, if I run in Google Chrome or Page Inspector all goes well, if I run in the current IE 10 I get an exception on the last line:
(function (root) {
var ko = root.ko,
breeze = root.breeze,
logger = root.app.logger;
// service name is route to the Web API controller
var serviceName = 'api/BreezeSample';
// manager is the service gateway and cache holder
var manager = new breeze.EntityManager(serviceName);
Essentially root.breeze is undefined, any idea why this is happening? How would the browser influence that?
How would I fix it? (I'm using VS 2012 Express for Web with all the updates loaded)
Adriaan,
I tried to replicate your error but could not. Here are the steps I used to get it up and running in IE10 (also using VS Express 2012 for Web):
File
New Project...
ASP.NET MVC 4 Web Application (Visual C#)
Empty
Tools
Library Package Manager
Manage NuGet Packages for Solution...
Search for Breeze.
Install Breeze for ASP.NET MVC4 Web Api Sample.
Ok
I Accept
Close
F5
Everything worked as expected.
I know it isn't the same error you are having, but if it makes you feel better, I failed out the first time I tried this as I selected ASP.NET MVC 4 Web Application (Visual Basic) instead of the C# version. Sure to fail and embarrassing once I realized the mistake.

Resources