So after a great deal of research I'm starting to enhance our service server stack with a webAPI entry point. Based on this thread, and especially the last post by a member of the Digerati board, we are implementing webAPI services as a facade into our WCF application layer. (Our WCF services are just facades into our Application layer where all of the behavior lives)
My question is this. I downloaded MVC 4 and created a new WebAPI project in my service solution. But wow there was a ton of crap that created in my project that I just am not going to need! For example, all of the image files, the home controller, views and models, etc.
So in stripping this down to be just a service project, what are the minimum files I need to build a functional service project? Our intent is to publish both of the service types (WCF and webAPI) side by side in the same server .. each service call doing the same identical service call and returning the specific DTO for the request. So far it looks like App_Start, Controllers, and the Glabal.asax/web.config entries. I definitely don't need Views, Models, or Images!!!
Any input on what others have done to do a pure service deployment would be of great welcome here.
Same problem here. I've found that article from Shawn Kendrot explaining how to create minimal Web API project. It was written for the beta version of Web API but it seems to be still valid.
Create an empty ASP.NET project.
Add a reference to System.Web.Http and System.Web.Http.WebHost (version 4.0.0.0)
Add a Global.asax file
Register a route in the Global.Application_Start. Something like:
protected void Application_Start(object sender, EventArgs e)
{
GlobalConfiguration.Configuration.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional });
}
Add a controller
public class SampleController : ApiController
{
public string Get(int id)
{
return "Hello";
}
}
Run the project locally with the URL /api/sample/123 and enjoy the outcome:
FYI. I have found that I have had to reference two more .dlls:
System.Net.Http
Newtonsoft.Json
Related
I'm trying to choose between MVC and WebApi, so some situations WebApi is better (documentation, testing and ...) and for some situation MVC controllers are better (when rendering Razor pages and so on)
But when I create an asp.net MVC webapplication, none of controllers inhertited from ApiController will be detected and If I create an asp.net WebApi web application, none of Controllers inheriting from System.Web.Mvc.Controller will be detected.
I compared web.config of these 2 web apps, nothing is different.
I have 2 questions
If both web.config are same, then how one app detects only controllers inherit from System.Web.Mvc.Controller and another app detects only controllers inherit from ApiController? what's different between them?
Can I configure web app to support both controller types?
If you right click and "go to definition" of both controllers you will discover they are of different namespaces and even implement different base classes, so you won't be able to have a class inherit from both "ApiController" (Web-Api) & "Controller"(MVC) at the same time (I much as I know).
However, if you need both controllers in the same projects, you can just right-click and add either a "Web-Api" controller or "MVC controller".
And then you can actually instantiate and use the "Web-Api" controller on the MVC controller code
The steps You needed to perform were:
1- Make Mvc Web Application Add reference to System.Web.Http.WebHost.
2- Add App_Start\WebApiConfig.cs (see code snippet below).
3- Import namespace System.Web.Http in Global.asax.cs.
4- Call WebApiConfig.Register(GlobalConfiguration.Configuration) in MvcApplication.Application_Start() (in file Global.asax.cs), before registering the default Web Application route as that would otherwise take precedence.
5- Add a controller deriving from System.Web.Http.ApiController.
I could then learn enough from the tutorial (Your First ASP.NET Web API) to define my API controller.
App_Start\WebApiConfig.cs:
using System.Web.Http;
class WebApiConfig
{
public static void Register(HttpConfiguration configuration)
{
configuration.Routes.MapHttpRoute("API Default", "api/{controller}/{id}",
new { id = RouteParameter.Optional });
}
}
Global.asax.cs:
using System.Web.Http;
...
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
WebApiConfig.Register(GlobalConfiguration.Configuration);
RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
the NuGet package Microsoft.AspNet.WebApi must be installed for the above to work.
I have an existing asp.net-mvc web site and now I need to expose of a few of my calls to external applications that are only used within my site right now. This is all happening within an intranet within my company.
I have read this page which explains Web API versus controller actions as well as this SOF question which seems to have a similar issue but the answers seem a bit outdated. So I am trying to determine given the latest available functionality what is the simplest solution to meet my requirement.
In my case, since I already have the same controller actions used within my current website then WEB API doesn't really make sense but if I google anything around asp.net-mvc authentication or security I only see articles around web API.
Given that, I am trying to figure out best practice for exposing my controller action to another application.
In an ideal world you would convert the app to web api controllers as someone else suggested but to be more pragmatic you can implement an interim solution where you expose only the required calls via extending ApiController
You did not mention which version of MVC your current app is using nor did you mention how your current Controllers return data to the web app.
I will therefore assume you return data via a view model and razor views. eg:
public class ProductsController : Controller
{
public void Index()
{
var view = new ProductsListView();
view.Products = _repository.GetProducts();
return View(view);
}
}
Suppose now you want to expose the products list via a REST-like api?
First check you have web api installed (via nuget)
Install-Package Microsoft.AspNet.WebApi
(again i'm not sure what ver of asp.net you are on so this process may differ between versions)
Now in your public void Application_Start()
GlobalConfiguration.Configure(WebApiConfig.Register);//add this before! line below
RouteConfig.RegisterRoutes(RouteTable.Routes);//this line shld already exist
and in WebApiConfig
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
I like to create a dedicated folder called ApiControllers and add controllers with the same name; this way you can have controllers with the same names as they are in different namespaces:
namespace YourApp.Web.ApiControllers
{
[AllowAnonymous]
public class ProductsController : ApiController
{
[HttpGet]
public HttpResponseMessage Products()
{
var result = new ProductResult();//you could also use the view class ProductsListView
result.Products = _repository.GetProducts();
return Request.CreateResponse(httpStatusCode, result);
}
}
}
You can then access this via yourapp.com/api/products
nb, try to reduce duplication of code inside controllers - this can be acheived by extracting common parts into service classes.
While I would highly recommend using a web service architecture, such as Web API or ServiceStack, you can expose controller actions.
You'll first want to decorate the actions with the [AllowAnonymous] attribute. Then, in your web.config you'll need to add the following code block to the configuration section for each action you want exposed.
<location path="ControllerNameHere/ActionNameHere">
<system.web>
<authorization>
<allow users="*" />
</authorization>
</system.web>
</location>
As you may have guessed, this becomes very repetitive and annoying, which is why web services would be a great choice.
I had a similar requirement where website 2 needed to call some controller actions from website 1. Since there was no changes in the logic I wanted to avoid the whole rewrite using web API. I created another set of controller and actions that would return Json. The new controller actions would call the original controller actions and then convert the result data to json before returning. The other applications (website 2) would then make http get and post requests to get json data and deserialize it internally. Worked nicely in my case.
I didn't have to put a security layer over the json based actions as they were public, but you might need one to authenticate the requests.
Although webapi is the best way but you don't need to convert your controller/actions to webapi at all.
You could easily achieve what you are after by restricting the controller/actions by IP addresses from your intranet. Just make sure that all intranet sites reside on the same domain other cross domain jquery ajax calls will not work.
Here is an eg. Restrict access to a specific controller by IP address in ASP.NET MVC Beta
An alternative is to use basic authentication and only allow a hardcoded userid/password to access those controller/actions and call via ajax:
beforeSend: function (xhr) {
xhr.setRequestHeader ("Authorization", "Basic " + btoa(username + ":" + password));
},
I'm really new to WebApi and I've been reading information about it but I don't know how to start my application.
I already had a project with many WFC services with .Net 3.5. So, I updated my project to 4.5.1. Then I created a controller with the Visual Studio 2012 Wizard. Then, when the controller is created, I see a class as a template with the get, post, put, delete methods. So I place my post method and finally I want to test the service with a HttpClient.
I tried to apply the solution in green from the following forum:
How to post a xml value to web api?
I'm gonna receive a XML string with the structure of a Contract model.
I run my project into Visual Studio Development Server.
But I have troubles with URL to test my service.
I saw many pages where people do something like this http://localhost:port/api/contract. But I don't still know how it works. So how can I do to test my service? What is it my path or url to test my service?
WebApi, like MVC, is all based on the routing. The default route is /api/{controller}/{id} (which could, of course, be altered). This is generally found in the ~/App_Start/WebApiConfig.cs file of a new project, but given you're migrating you don't have it most likely. So, to wire it up you can modify your Application_Start to include:
GlobalConfiguration.Configure(WebApiConfig.Register);
Then, define that class:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
If you created a TestController controller and wanted to make a POST request to the instance running locally, you'd access http://localhost:12345/api/Test/ (with the appropriate verb). 12345 would be the local port that Visual Studio is using to host your service (and can be found by viewing the project's properties, then navigating to the "Web" tab).
Having said that, testing is probably best performed on the the project (without making an external call). There are several posts on the subject, but generally come down to something like the following:
[TestMethod]
public void Should_Return_Single_Product()
{
// Arrange
var repo = new FakeRepository<Widget>();
var controller = new WidgetController(repo);
var expected = repo.Find(1);
// Act
var actual = controller.GetWidget(1) as OkNegotiatedContentResult<Widget>;
// Assert
Assert.IsNotNull(actual);
Assert.AreEqual(expected.Id, actual.Content.Id);
}
I used to place my controllers into a separate Class Library project in Mvc Web Api. I used to add the following line in my web api project's global.asax to look for controllers in the separate project:
ControllerBuilder.Current.DefaultNamespaces.Add("MyClassLibraryProject.Controllers");
I never had to do any other configuration, except for adding the above line. This has always worked fine for me.
However I am unable to use the above method to do the same in WebApi2. It just doesn't work. The WebApi2 project still tries to find the controllers in its own project's controllers folder.
-- Giving little summary update after 2 months (As I started bounty on this):
I have created a WebApiOne solution, it has 2 projects, the first one is WebApi project, and the second is a class library for controllers. If I add the reference to the controllers class library project into the WebApi project, all works as expected. i.e. if i go to http://mydevdomain.com/api/values i can see the correct output.
I have now create a second project called WebApiTwo, it has 2 projects, the first one is WebApi2 project, and the second is a class library for controllers. If I add the reference to the controllers class library project to the WebApi2 project, it doest NOT work as expected. i.e. if i go to http://mydevdomain.com/api/values i get "No type was found that matches the controller named 'values'."
for the first project i am not doing any custom settings at all, i do NOT have:
ControllerBuilder.Current.DefaultNamespaces.Add("MyClassLibraryProject.Controllers");
in my global.asax, and i have not implemented any custom solutions proposed by StrathWeb in two of his blog posts, as i think its not applicable any more; because all works just by adding the reference of the controller project to the WebApi project.
So i would expect all to work same for WebApi2 ... but its not. Has anyone really tried doing this in WebAPi2 ?
I have just confirmed that this works fine. Things to check:
References: Does your main Web API project reference the external class library?
Routing: Have you set up any routes that might interfere with the external controllers?
Protection Level: Are the controllers in the external library public?
Inheritance: Do the controllers in the external library inherit from ApiController?
Versioning: Are both your Web API project and class library using the same version of the Web API libraries?
If it helps, I can package up my test solution and make it available to you.
Also, as a point to note, you don't need to tell Web API to find the controllers with the line you added to Global.asax, the system finds the controllers automatically provided you have them referenced.
It should work as is. Checklist
Inherit ApiController
End controller name with Controller. E.g. ValuesController
Make sure WebApi project and class library project reference same WebApi assemblies
Try to force routes using attribute routing
Clean the solution, manually remove bin folders and rebuild
Delete Temporary ASP.NET Files folders. WebApi and MVC cache controller lookup result
Call `config.MapHttpAttributeRoutes(); to ensure framework takes attribute routes into consideration
Make sure that the method you are calling is made to handle correct HTTP Verb (if it is a GET web method, you can call via browser URL, if it is POST you have to otherwise craft a web request)
This controller:
[RoutePrefix("MyValues")]
public class AbcController : ApiController
{
[HttpGet]
[Route("Get")]
public string Get()
{
return "Ok!";
}
}
matches this url:
http://localhost/MyValues/Get (note there is no /api/ in route because it wasn't specified in RoutePrefix.
Controller lookup caching:
This is default controller resolver. You will see in the source code that it caches lookup result.
/// <summary>
/// Returns a list of controllers available for the application.
/// </summary>
/// <returns>An <see cref="ICollection{Type}" /> of controllers.</returns>
public override ICollection<Type> GetControllerTypes(IAssembliesResolver assembliesResolver)
{
HttpControllerTypeCacheSerializer serializer = new HttpControllerTypeCacheSerializer();
// First, try reading from the cache on disk
List<Type> matchingTypes = ReadTypesFromCache(TypeCacheName, IsControllerTypePredicate, serializer);
if (matchingTypes != null)
{
return matchingTypes;
}
...
}
Was running into same scenario and #justmara set me on the right path. Here's how to accomplish the force loading of the dependent assemblies from #justmara's answer:
1) Override the DefaultAssembliesResolver class
public class MyNewAssembliesResolver : DefaultAssembliesResolver
{
public override ICollection<Assembly> GetAssemblies()
{
ICollection<Assembly> baseAssemblies = base.GetAssemblies();
List<Assembly> assemblies = new List<Assembly>(baseAssemblies);
var controllersAssembly = Assembly.LoadFrom(#"Path_to_Controller_DLL");
baseAssemblies.Add(controllersAssembly);
return baseAssemblies;
}
}
2) In the configuration section, replace the default with the new implementation
config.Services.Replace(typeof(IAssembliesResolver), new MyNewAssembliesResolver());
I cobbled this syntax together using pointers from this blog:
http://www.strathweb.com/2013/08/customizing-controller-discovery-in-asp-net-web-api/
As others have said, you know if you are running into this issue if you force the controller to load by directly referencing it. Another way is to example the results of CurrentDomain.GetAssemblies() and see if your assembly is in the list.
Also: If you are self-hosting using OWIN components you WILL run into this. When testing keep in mind that the DefaultAssembliesResolver will NOT kick in until the first WebAPI request is submitted (it took me awhile to realize that).
Are you sure that your referenced assembly was loaded BEFORE IAssembliesResolver service called?
Try to insert some dummy code in your application, something like
var a = new MyClassLibraryProject.Controllers.MyClass();
in configuration method (but don`t forget, that compiler can "optimize" this code and totally remove it, if "a" is never used).
I've had similar issue with assembly loading order. Ended up with force loading dependent assemblies on startup.
You need to tell webapi/mvc to load your referrenced assembly. You do that with the compilation/assemblies section in your web.config.
<compilation debug="true" targetFramework="4.5.2">
<assemblies>
<add assembly="XYZ.SomeAssembly" />
</assemblies>
</compilation>
Simple as that. You can do it with code the way #user1821052 suggested, but this web.config version will have the same effect.
Apart from what has been said already:
Make sure you don't have two controllers of the same name in different namespaces.
Just had the case where one controller (foo.UserApiController) should be partially migrated to a new namespace (bar.UserApiController) and URI. The old controller was mapped by convention to /userapi, the new one was attribute-routed via RoutePrefix["api/users"]. The new controller didn't work until I renamed it to bar.UserFooApiController.
When using AttributeRouting it is easily forgettable to decorate your methods with the Route Attribute, especially when you are using the RoutePrefix Attribute on your controller class. It seems like your controller assembly wasn't picked up by the web api pipeline then.
If your class library is built with EF then make sure you have the connection string specified in the App.config for the class library project, AND in the Web.config for your Web API MVC project.
I am creating a RESTful webservice using ASP.NET MVC (not ASP.NET Web API). What I want to do is have every method in the controller return their result based on an input parameter (i.e. json or xml).
If I were using ASP.NET Web API, the HttpResponseMessage works for this purpose. When I attempt to return an HttpResponseMessage from a controller in ASP.NET MVC, there is no detail.
I have read that in this approach, I am supposed to use ActionResult. If I do this, then I need to create an XmlResult that inherits from ActionResult since it is not supported.
My question is why HttpResponseMessage does not work the same in both situations. I understand that in Web API, we inherit from ApiController and in ASP.NET MVC we inherit from System.Web.Mvc.Controller.
Any help is greatly appreciated.
Thanks,
EDIT 1
Much thanks to Fals for his input. My problem was in how to create an empty website and add all of the necessary functionality in. The solution was to use Nuget to get the packages mentioned in the comments and then to follow the steps in How to integrate asp.net mvc to Web Site Project.
Web Api is a Framework to develop Restfull services, based on HTTP. This framework was separeted into another assembly System.Web.Http, so you can host it everywhere, not only in IIS. Web API works directly with HTTP Request / Response, then every controller inherit from IHttpController.
Getting Started with ASP.NET Web API
MVC has It's implementation on System.Web.Mvc. coupled with the ASP.NET Framework, then you must use It inside an Web Application. Every MVC controller inherits from IController that makes an abstraction layer between you and the real HttpRequest.
You can still access the request using HttpContext.Response directly in your MVC controller, or as you said, inheriting a new ActionResult to do the job, for example:
public class NotFoundActionResult : ActionResult
{
private string _viewName;
public NotFoundActionResult()
{
}
public NotFoundActionResult(string viewName)
{
_viewName = viewName;
}
public override void ExecuteResult(ControllerContext context)
{
context.HttpContext.Response.StatusCode = 404;
context.HttpContext.Response.TrySkipIisCustomErrors = true;
new ViewResult { ViewName = string.IsNullOrEmpty(_viewName) ? "Error" : _viewName}.ExecuteResult(context);
}
}
This ActionResult has the meaning of respond thought HTTP Error.
As a matter of fact, it is indeed possible. You basically have two options:
develop your custom ActionResult types, which can be an heavy-lifting work and also quite hard to mantain.
add WebAPI support to your website.
I suggest you to do the latter, so you will have the best of two worlds. To do that, you should do the following:
Install the following Web API packages using NuGet: Microsoft.AspNet.WebApi.Core and Microsoft.AspNet.WebApi.WebHost.
Add one or more ApiControllers to your /Controllers/ folder.
Add a WebApiConfig.cs file to your /App_Config/ folder where you can define your Web API routing scheme and also register that class within Global.asax.cs (or Startup.cs) file.
The whole procedure is fully explained here: the various steps, together with their pros-cons and various alternatives you can take depending on your specific scenario, are documented in this post on my blog.