asp net httpselfhostserver for controllers that do not extend ApiController - c#

Hi I am new to asp net programming and I am trying to test my asp net application using HttpSelfHostServer
link: http://www.c-sharpcorner.com/UploadFile/2b481f/self-hosting-in-Asp-Net-web-api/
by first setting up the server and then calling GET requests on my server on different controllers. (as described in the link)
This works perfectly when the controllers extend ApiController (which seems to be the base for asp net webapi applications) but it doesnt work for any other controller.
I am trying to get this to work with controllers that return views such as :
public class HomeController
: Controller
{
public ViewResult Index()
{
return View();
}
}
IS this not possible to do with the HttpSelfHostServer? Is there a workaround to this?

Related

ASP.NET Core MVC Web API deployment issues

I'm trying to deploy my ASP.NET Core MVC Web App with Web API, i.e. I have both MVC and API controllers in the same folder.
It works fine on localhost but on IIS when I create a Virtual Directory, the path gets added to the domain.
I can find it using window.location.pathname
I can append the 'api/Get' and it works like (questions is my virtual directory)
http://example.com/questions/api/Question/GetAll
But when I navigate to other pages then then controller name also gets appended and then it causes issues.
e.g. if I navigate to the 'Question' page (QuestionController), the URL becomes
http://example.com/questions/newquestion/api/Question/Create
instead of
http://example.com/questions/api/Question/Create
How can I fix it?
Here is my Asp.Net core api.
[ApiController]
public class ScheduleController : ControllerBase
{
[HttpGet]
public List<PathologistSchedule> GetPathologistScheduleByDate(DateTime taskDate)
{
return pathologistRepository.GetPathologistScheduleByDate(taskDate).ToList();
}
}
I call this api from PathologistScheduleController's view using jquery.
Here's the error I get:
GET http://localhost:51434/PathologistSchedule/api/Schedule/?sort=&group=&filter=&taskDate=2020-11-13T21%3A16%3A47.507Z 404 (Not Found)
TIA.
A
If you have API and MVC projects in one solution you have to config your solution to run multiple projects.
You can use route attribute like this for each of your APIs
[Route("~/api/Question/GetAll")]
will give you Url http://example.com/api/Question/GetAll.
Or
[Route("~/api/Question/Create")]
will give Url http://example.com/api/Question/Create.
And it will not depend on the controller name or folder.
UPDATE because of the question update:
Use this code please:
public class ScheduleController : ControllerBase
{
[Route("~/api/Schedule/GetPathologistScheduleByDate/{taskDate?}")]
public List<PathologistSchedule> GetPathologistScheduleByDate(DateTime taskDate)
{
return pathologistRepository.GetPathologistScheduleByDate(taskDate).ToList();
}
}
for testing try this route in your browser:
http://localhost:51434/api/Schedule/GetPathologistScheduleByDate/2020-11-13T21%3A16%3A47.507Z
But basically for APIs you don't need to use any controller or action name. You can use any names you like, for example:
[Route("~/api/Pathologist/GetSchedule/{taskDate?}")]
or
[Route("~/api/GetPathologistSchedule/{taskDate?}")]
or even
[Route("~/api/{taskDate?}")]
The route just should be unique.
I added a variable in the 'appsettings.json' and 'appsettings.Development.json' called baseURL and had 'appsettings.json' set to '/VirtualDirectoryName/' and kept the one in 'appsettings.Development.json' as '/'.
Appended this variable when calling APIs.

Asp.net core - Web Api on Class Library

I am trying to make n-tier application where web api is kept on a different class library. I made a TestController controller class in a different class library and my code goes like this
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
namespace PkrUni.SMS.Api
{
[ApiController]
[Produces("application/json")]
[Route("api/[controller]")]
public class TestController : ControllerBase
{
public IEnumerable<string> Get()
{
return new string[] { "Chris", "Hadfield" };
}
}
}
Now my question is how can I access this web api on my main project. I had already added a reference to that class library on main project but it doesn't working. My api is not working. 404 Page Not Found error shows up while trying to access the api.
This is my project structure.
What am I doing wrong please help me.
Try to install Microsoft.AspNetCore.Mvc package in the razor class library.
And in startup.cs use:
services.AddMvc().AddApplicationPart(Assembly.Load(new AssemblyName("PkrUni.SMS.Area.Api")));
Refer to here.
I test your scenario by creating a asp.net core2.2 MVC project and razor class library without any problem. Below is my structure:

User ID is NULL when consuming an API in POSTMAN

I am trying to learn Web API and MVC. I, initially created a basic MVC project. Now, in the controllers folder ,I added a WebAPI controller.
In the WebAPI controller, I added the below code
public class SampleController : ApiController
{
[HttpPost]
public IHttpActionResult SampleData()
{
var userID = User.Identity.GetUserId();
return Ok();
}
}
The Method User.Identity.GetUserId() works fine in MVC.
I searched about on SO and found the following thread
User.Identity.GetUserId() method not working in a Web Api 2 Controller
This was not that helpful for me, as in my case I have added the API controller as part of the MVC project itself in the controllers folder.I have not created a separate project for WebAPI.
The above mentioned thread talks about the accesstoken already being present in code , whereas in my case, I dont see that code anywhere, as I just added only a single web api controller.
I am using POSTMAN for calling the API.
I have also looked at the following link
https://learn.microsoft.com/en-us/aspnet/web-api/overview/security/individual-accounts-in-web-api
In this case too, a separate WebAPI project is being talked about and not a single controller.
If I am mistaken somewhere, kindly guide me on the same.

IntegrationTest controllers with .net core 2.0 on web api

I've just created an empty web api project with .net core 2.0.
I have a default controller and I want now create an integration test.
[Route("api/[controller]")]
public class ValuesController : Controller
{
// GET api/values
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
}
The goal is self host in the integration then enter url api/values and check the return.
NB: I only use wep api 2 and owin, and it was quite easy to do this. But the following link: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/owin says that .net core application should not use owin, so what should we use and how to it?
Take a look at the official documentation for integration testing with ASP.NET Core 2.0: https://learn.microsoft.com/en-us/aspnet/core/testing/integration-testing
The main idea is to create a TestServer instance with a WebHostBuilder configured with your Startup class. You can then get a HttpClient instance from the TestServer to call your self-hosted api

Problems trying to return the view with an API controller

I'm implementing a REST Web API. I'm using the examples from Adam Freeman's Pro ASP.NET MVC5 as a starting point but adapting it into the Web API way of doing it.
The below is my code:
public class AdminController : ApiController
{
private IUserRepository _repository;
public AdminController(IUserRepository repository)
{
_repository = repository;
}
public ActionResult Index()
{
return View(_repository.Users);
}
}
In the book, AdminController implemented Controller not ApiController, but if I do that then I get errors about there being no parameterless constructor. I need the constructor to take parameters so that I can inject the dependencies. So that's why I changed to ApiController but now it won't recognise View.
What do I need to use instead of View for an ApiController?
I did find this question but the answer was basically "you don't need to use an ApiController here, just use Controller" so that didn't help me.
You are having two different problems. Let's solve them separately.
1. Do I need to use ApiController or Controller?:
Someone already answered this here: Difference between ApiController and Controller in ASP.NET MVC.
The first major difference you will notice is that actions on Web API
controllers do not return views, they return data.
ApiControllers are specialized in returning data. For example, they
take care of transparently serializing the data into the format
requested by the client.
So, if you want to return a View you need to use the simple ol' Controller. The WebApi "way" is like a webservice where you exchange data with another service (returning JSON or XML to that service, not a View). So whenever you want to return a webpage (View) for a user you don't use the Web API.
In other words, the Web API is about returning data to another service (to return a JSON or XML), not to a user.
2. But if I use Controller then I get "parameterless constructor" errors.
Okay, now we've got to your real problem. Don't try to reinvent the wheel and fight with ASP.NET about doing dependency injection! A tool already exists to resolve dependency injection and sort out the "parameterless constructor" error: Ninject.
If you're already using Ninject and still getting that error, you're doing something wrong with Ninject. Try to repeat the installation and configuration steps, and see some tutorials or questions about parameterless error with Ninject use
An API controller is a controller which provides a RESTful response. You cannot return a view from it. Instead of doing that, consider returning a response (values) which forces the client that asks for an action to redirect to another controller (passing arguments if necessary) to return a view.
Your case does not look like you need an API; in this case just try this (change what you inherit):
public class AdminController : Controller
{
private IUserRepository _repository;
public AdminController(IUserRepository repository)
{
_repository = repository;
}
public ActionResult Index()
{
return View(_repository.Users);
}
}
I will try to explain what an API should do anyway. A web API should return just information. An HTTP response about what the action should do.
For example, to create a new customer, an API should have a method (decorated with POST) to get information from a client application (could be anything: web, windows, mobile, windows service, etc.). This information should be processed by the API (or other layers in a possible architecture) and return an HTTP status code, for example 200 - OK if it was fine or 400 - Bad Request if an error happened. So, when I said you should consider returning information, you could just return a DTO object to provide a result.
Both types of project use MVC principles, but they are used in a different context. Take a look at these articles:
Web Api 2.0 Tutorial
Difference between MVC and WEB API
Also take a look at the ASP.NET website about how they work:
ASP.NET WEB API
ASP.NET MVC
Use Controller to render your normal views. ApiController action only return data that is serialized and sent to the client.
But still you want to render view from APIcontroller, then there may be a another way, click on below link for reference :
https://aspguy.wordpress.com/2013/09/10/web-api-and-returning-a-razor-view/

Categories